graphics2d api整理(列举一些经常使用的)
/**
* 创建画板
*/
public Graphics2D createGraphics();
/**
* 渲染效果配置
*/
public abstract void setRenderingHint(Key hintKey, Object hintValue);
/**
* 设置画笔颜色
*/
public abstract void setPaint( Paint paint );
/**
* 设置文字样式
*/
public abstract void setFont(Font font);
/**
* 往画板上填充图片,observer一般设置为null
*/
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer);
/**
* 往画板上写字
*/
public abstract void drawString(String str, int x, int y);
/**
* 画矩形
*/
public void drawRect(int x, int y, int width, int height);
/**
* 填充矩形
*/
public abstract void fillRect(int x, int y, int width, int height);
/**
* 画圆弧 startAngle=90时指向北方,逆时针方向画线
*/
public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle);
/**
* 填充扇形 startAngle=90时指向北方,逆时针方向填充
*/
public abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle);
/**
* 画椭圆 width = height时为圆
*/
public abstract void drawOval(int x, int y, int width, int height);
/**
* 填充椭圆
*/
public abstract void fillOval(int x, int y, int width, int height);
public class CircularDemo {
private static final String STORE_PATH = "/opt/study/result.png";
private static final String TEMPLATE_PATH = "/opt/study/template.jpeg";
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
BufferedImage image = ImageIO.read(new File(TEMPLATE_PATH));
// create graphics
Graphics2D graphics = image.createGraphics();
// set graphics profile
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
// draw circular
graphics.setPaint(Color.BLUE);
graphics.drawArc(200,200,200,200,90,450-30);
graphics.fillArc(200,200,200,200,90,450-30);
// draw sector
graphics.setPaint(Color.RED);
graphics.drawArc(200,200,200,200,90-30,30);
graphics.fillArc(200,200,200,200,90-30,30);
// store and end
graphics.dispose();
ImageIO.write(image, "PNG", new File(STORE_PATH));
System.out.println(System.currentTimeMillis()-start);
}
}
附录
- 配置font字体时不知道有哪些?先用下面这段代码打印一下所有的字体
public class FontDemo {
public static void main(String[] args) {
Font[] fonts = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getAllFonts();
for (Font font : fonts) {
System.out.println(font.getFontName());
}
}
}