绘制、保存图形
耿祥义
我们绘制一个圆和一个太极图,并将绘制的图形保存成图像。保存的太极图和圆的图像如下图所示意。
一、涉及的主要知识点见教材第14章
BufferedImage类的对象称作一个缓存图像。缓存图像自带一个 Graphics对象,该对象可以向缓存图像上绘制图形。
2.java.awt.Graphics类
Graphics类提供了各种绘制图形的方法。
3.java.awt.Graphics2D类
Graphics2D类提供的draw(Shape shape)和fill(Shape shape)方法可以绘制或填充实现Shape接口的类的实例,即可以绘制各种图形对象,例如,Ellipse2D椭圆图形对象。
4.javax.imageio.ImageIO
ImageIO类的静态方法:
public static boolean write
(RenderedImage im,
String formatName,
File output)
将图像im写入到文件output。formatName参数指定图像的编码格式,例如:"jpeg","bmp"等。
im必须是实现RenderedImage接口的类的实例(BufferedImage类实现了RenderedImage接口)。
二、视频讲解
将
https://share.weiyun.com/3Qe3AN5W
复制到浏览器地址栏访问即可。
接口:Drawer.java
public interface Drawer {
BufferedImage getImage();
}
实现接口的类:DrawCircle.java负责绘制圆到缓存图像
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Color;
//负责绘制圆:
public class DrawCircle implements Drawer {
public BufferedImage getImage(){
int width=320, height=300;
int r = 110;
BufferedImage image =
new BufferedImage
(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//g默认用白色绘制图形
g.fillRect(0, 0, width, height);
Graphics2D g_2d=(Graphics2D)g;
Ellipse2D ellipse=
new Ellipse2D.Double(160-r,150-r,2*r,2*r);
g_2d.setColor(Color.blue);
g_2d.draw(ellipse);
return image;
}
}
实现接口的类:DrawTaiJi.java负责绘制太极图到缓存图像
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Color;
//负责绘制太极图:
public class DrawTaiJi implements Drawer {
public BufferedImage getImage(){
int width=300, height=300;
int r = width/8;
BufferedImage image =
new BufferedImage
(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.gray);
//设置图像是灰色底色(默认是黑色):
g.fillRect(0, 0, width, height);
Graphics2D g_2d=(Graphics2D)g;
Arc2D arc=
new Arc2D.Double
(0,0,width,height,-90,-180,Arc2D.PIE);
g_2d.setColor(Color.black);
g_2d.fill(arc);
g_2d.setColor(Color.white);
arc.setArc
(0,0,width,height,-90,180,Arc2D.PIE);
g_2d.fill(arc);
arc.setArc
(width/4,0,width/2,height/2,-90,-180,Arc2D.PIE);
g_2d.fill(arc);
g_2d.setColor(Color.black);
Ellipse2D ellipse=
new Ellipse2D.Double
(width/2-r/2,height/4-r/2,r,r);
g_2d.fill(ellipse);
arc.setArc
(width/4,height/2,width/2,height/2,90,-180,Arc2D.PIE);
g_2d.fill(arc);
g_2d.setColor(Color.white);
ellipse.setFrame
(width/2-r/2,3*height/4-r/2,r,r);
g_2d.fill(ellipse);
return image;
}
}
负责将图形保存为图像的类:MakeImage.java
import javax.imageio.ImageIO;
import java.io.File;
public class MakeImage {
public static void drawAndSaveGeometry
(Drawer drawer, String formatName,File imageFile) {
try {
boolean boo =
ImageIO.write
(drawer.getImage(),formatName,imageFile);
}
catch(Exception exp){}
}
}
主类:MainClass.java
import java.io.File;
public class MainClass {
public static void main(String args[]){
Drawer drawer = new DrawCircle();
File f = new File("circle.jpg");
//保存一个圆图像circle.jpg
MakeImage.drawAndSaveGeometry
(drawer,"jpeg",f);
drawer = new DrawTaiJi();
f = new File("taiji.bmp");
//保存一个太极图像taiji.bmp
MakeImage.drawAndSaveGeometry
(drawer,"bmp",f);
}
}
领取专属 10元无门槛券
私享最新 技术干货