- 328
- 0
- 约 49页
- 2017-09-27 发布于海南
- 举报
g.draw(rect); rect = new Rectangle2D.Float(100,100,40,40); g.fill(rect); //画椭圆 Ellipse2D ellipse = new Ellipse2D.Float(120,120,30,40); g.draw(ellipse); gt = new GradientPaint(0,0,Color.red,30,30,Color.yellow,true); g.setPaint((Paint)gt); ellipse = new Ellipse2D.Float(140,140,20,20); g.fill(ellipse); //画圆角矩形 RoundRectangle2D roundRect = new RoundRectangle2D.Float(160,160,40,40,20,20); g.draw(roundRect); roundRect = new RoundRectangle2D.Float(180,180,40,40,20,20); g.fill(roundRect); //画几何图形 GeneralPath path = new GeneralPath(); path.moveTo(150,0); path.lineTo(160,50); path.curveTo(190,200,240,140,200,100); g.fill(path); } } 图4 通过Graphics2D对象绘制形状 5.2 绘制文本 Graphics2D类提供一个文本布局(TextLayout)对象,用于实现各种字体或段落文本的绘制。其构造函数为: public TextLayout(String string, Font font, FontRenderContext frc) 通过字符串string和字体font构造布局。 public void draw(Graphics2D g2, float x, float y) 将这个TextLayout对象画到Graphics2D对象g2上的x,y坐标处。 public Rectangle2D getBounds() 返回TextLayout对象的区域。 【例4】测试绘制文本功能,如图5所示。源程序代码如下: //程序文件GUIText.java import java.awt.*; import java.applet.*; import java.awt.geom.*; import java.awt.font.*; public class GUIText extends Applet { public void paint(Graphics oldg) { Graphics2D g = (Graphics2D)oldg; //设置字体 Font f1 = new Font(Courier,Font.PLAIN,24); Font f2 = new Font(helvetica,Font.BOLD,24); FontRenderContext frc = g.getFontRenderContext(); String str = new String(这是一个文本布局类的实现); String str2 = new String(扩充绘制文本的功能); //构造文本布局对象 TextLayout layout = new TextLayout(str, f1, frc); Point2D loc = new Point2D.Float(20,50); //绘制文本 layout.draw(g, (float)loc.getX(), (float)loc.getY()); //设置边框 Rectangle2D bounds = layout.getBounds(); bounds.setRect(bounds.getX()+loc.getX(), bounds.getY()+loc.getY(), bounds.getWidth(), bounds.getHeight()); g.draw(bounds); layout = new TextLayout(str2,f2,frc); g.setColor(Color.red); layout.draw(g,20,80); } } 图5 Graphics2D对象绘制文本 5.3 绘制图像
原创力文档

文档评论(0)