记得那些年我们玩过的头像+1,恶作剧让朋友圈里的人都以为有人和他说话~
思路,刚学习完Swing,使用Java中Java2D图形操作库进行绘制
参考代码如下:
1 import javax.swing.*; 2 import java.awt.*; 3 import java.awt.font.*; 4 import java.awt.geom.*; 5 import java.util.Scanner; 6 7 /** 8 * Created by CAD on 2016/12/1. 9 */ 10 public class ImagePlusOne { 11 public static void main(String[] args){ 12 Scanner in = new Scanner(System.in); 13 String imageUrl = in.next(); //输入路径,注意转义 14 int num = in.nextInt(); //输入图中数字 15 EventQueue.invokeLater(new Runnable() { 16 @Override 17 public void run() { 18 JFrame frame = new ImageFrame(imageUrl,num); 19 frame.setTitle("imageTest"); 20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 frame.setVisible(true); 22 } 23 }); 24 } 25 } 26 27 class ImageFrame extends JFrame { 28 private Image image; 29 public ImageFrame(String url,int n){ 30 ImageComponent imageComponent = new ImageComponent(url,n); 31 add(imageComponent); 32 image = imageComponent.getImage(); 33 setSize(image.getWidth(this) + 45,image.getHeight(this) + 45); 34 setLocationByPlatform(true); 35 } 36 } 37 38 class ImageComponent extends JComponent { 39 private Image image; 40 private int num; 41 42 public ImageComponent(String url,int an){ 43 image = new ImageIcon(url).getImage(); 44 num = an; 45 } 46 47 public Image getImage() { 48 return image; 49 } 50 public void paintComponent(Graphics g){ 51 if (image == null) return ; 52 int imageWidth = image.getWidth(this); 53 int imageHeight = image.getHeight(this); 54 55 // draw the image int the upper-left corner 56 g.drawImage(image,0,0,null); 57 58 // 画圆 59 Graphics2D g2 = (Graphics2D)g; 60 double radius = imageHeight / 10; // 圆半径 61 double centerX = imageWidth - radius; 62 double centerY = radius; 63 Ellipse2D circle = new Ellipse2D.Double(); 64 circle.setFrameFromCenter(centerX,centerY,centerX + radius,centerY + radius); 65 g2.setPaint(Color.RED); // 设置颜色 66 g2.fill(circle); //填充圆颜色 67 68 String numTemp = ""; 69 if(num >= 100) 70 numTemp += "99+"; 71 else 72 numTemp += num; 73 74 // 设置字体 75 Font f = new Font("Arial",Font.BOLD,(int)radius); 76 g2.setFont(f); 77 78 // 得到包围字体的矩形,为了让字体近似居中 79 FontRenderContext context = g2.getFontRenderContext(); 80 Rectangle2D fontBounds = f.getStringBounds(numTemp,context); 81 82 double numX = centerX - fontBounds.getWidth() / 2; 83 double numY = centerY + fontBounds.getHeight() / 3; 84 g2.setPaint(Color.WHITE); 85 g2.drawString(numTemp,(int)numX,(int)numY); 86 } 87 }
图片处理结果如下: