16.18.6 渐变方框与文字 Cyclic GradientPaint

 16.18.6 渐变方框与文字 Cyclic GradientPaint_第1张图片

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Float;
import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;
import javax.swing.JFrame;


public class GradientPane extends JComponent{
	public void paint(Graphics g){
		Graphics2D g2d = (Graphics2D) g;
		Point2D.Float p1 = new Point2D.Float(150.f,75.f);//起点坐标
		Point2D.Float p2 = new Point2D.Float(250.f,75.f);
		float width = 300;
		float height = 50;
		GradientPaint g1 = new GradientPaint(p1,Color.green,p2,Color.black,true);
		
		Rectangle2D.Float rect1 = new Rectangle2D.Float(p1.x - 100,p1.y -25,width,height);
		g2d.setPaint(g1);//它是从150处开始绿色,正好是窗口的x/2:中心
		g2d.fill(rect1);//画方:从150-100=50处开始,宽300,高50
		
		g2d.setPaint(Color.PINK);
		g2d.draw(rect1);
		g2d.draw(new Line2D.Float(p1,p2));
		//p1 - 此线段的起始 Point2D   p2 - 此线段的结束 Point2D
		
		Font font = new Font("Dialog", Font.BOLD ,40);
		//FontMetrics 类定义字体规格对象,该对象封装将在特定屏幕上呈现特定字体的有关信息。
		FontMetrics fontMetrics = getFontMetrics(font);//metrics:度量、指标
		GradientPaint g2 = new GradientPaint(150.f,280.f,Color.blue,fontMetrics.stringWidth("Hello"),
				fontMetrics.getHeight(),Color.red);
		// 创建一个新 FontMetrics 对象,用于查找该 Font 中关于指定 Font 和特定字符字形的 height 和 width 信息。
		g2d.setFont(font);
		g2d.setPaint(g2);
		g2d.drawString("Hello", 150, 150);
	}

	public static void main(String[] args) {
		JFrame window = new JFrame("Cyclic Gradient Paint");
	    window.setBounds(30, 30, 300, 300);
	    window.getContentPane().add(new GradientPane());
	    window.setVisible(true);
	}

}


 

你可能感兴趣的:(String,Class,dialog,import,float,jcomponent)