JAVA Graphics2D画笔初体验 博客分类: JDK//Demo javaGraphics
程序员文章站
2024-03-16 17:06:16
...
import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Test { public static void main(String []args){ Test.pressFive("d:/generImage.png", 1, 0, 0, 0, 0); } /** * 生成五边形用的函数 * @param dstImg,输出图片文件名称 * @param v1,有效值为0-4 * @param v2,有效值为0-4 * @param v3,有效值为0-4 * @param v4,有效值为0-4 * @param v5,有效值为0-4 */ public final static void pressFive(String dstImg,int v1,int v2,int v3,int v4,int v5) { try { int picWidth=600,picHeight=600; BufferedImage bufferedImage = new BufferedImage(picWidth, picHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f)); //填充背景 g.setColor(new Color(255,255,255)); g.fillRect(0, 0, picWidth, picHeight); int min = 90,deta=20,mark=50; int [][]p1 = new int[5][2]; for(int i=0; i<5; i++){ p1[i][0]=picWidth/2; p1[i][1]=picHeight/2-min-deta*i; } int [][]px = new int[5][5]; //一维:五个角中的那个角,二维:从里到外0-4 int [][]py = new int[5][5]; double angle=0.0; //计算五个五边形的顶点。 for(int i=0; i<5; i++){ angle = 72*Math.PI*i/180; for(int j=0; j<5; j++){ px[i][j]=(int) Math.round(picWidth/2+(min+deta*j)*Math.sin(angle)); py[i][j]=(int) Math.round(picHeight/2-(min+deta*j)*Math.cos(angle)); } } //绘制五个五边形 g.setColor(new Color(128,128,128)); for(int i=0; i<5; i++){ g.drawPolygon(new int[]{px[0][i],px[1][i],px[2][i],px[3][i],px[4][i]}, new int[]{py[0][i],py[1][i],py[2][i],py[3][i],py[4][i]}, 5); } //绘制根据指定的顶点序号,绘制五边形 g.setColor(new Color(0,204,255)); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f)); g.fillPolygon(new int[]{px[0][v1],px[1][v2],px[2][v3],px[3][v4],px[4][v5]}, new int[]{py[0][v1],py[1][v2],py[2][v3],py[3][v4],py[4][v5]}, 5); //输出文字 g.setColor(new Color(16,16,16)); int fontsize=12; g.setFont(new Font("黑体",Font.PLAIN,fontsize)); String [] text = {"金","木","水","火","土"}; g.drawString(text[0]+"/"+(v1)*mark, px[0][4],py[0][4]-fontsize); g.drawString(text[1]+"/"+(v2)*mark, px[1][4],py[1][4]); g.drawString(text[2]+"/"+(v3)*mark, px[2][4],py[2][4]+fontsize); g.drawString(text[3]+"/"+(v4)*mark, px[3][4]-fontsize*7,py[3][4]); g.drawString(text[4]+"/"+(v5)*mark, px[4][4]-fontsize*7,py[4][4]); g.dispose(); //保存图片 ImageIO.write(bufferedImage, "JPG", new File(dstImg)); } catch (IOException e) { e.printStackTrace(); } } }
上一篇: leetcode 767. 重构字符串