来源:http://blog.csdn.net/rexih/article/details/46453527
Color & Font都是java.awt.*;下的类
颜色:
1.Color类预定义的13种颜色
Color.BLACK
Color.BLUE
Color.CYAN
Color.DARK_GRAY
Color.GRAY
Color.GREEN
Color.LIGHT_GRAY
Color.MAGENTA
Color.ORANGE
Color.PINK
Color.RED
Color.WHITE
Color.YELLOW
2.通过构造函数创建颜色对象
Color(int r,intg,int b)//rgb是0-255的int值,e.g.
Color c=new Color(128,0,255);
3.使颜色对象变亮/暗
c.brighter();/c.darker();
效果不是特别明显,需要连续调用才能达到耀眼的效果:
c.brighter().brighter().brighter();
brighter方法对预定义的13种颜色效果不好,也许是因为到颜色的值是极值
设置颜色:
1.设置之后绘制的图形都使用的颜色 Graphics2D
setPaint(Color c)
2.填充封闭图形的颜色,用fill替代draw Graphics2D
fill(Shape s)
3.设置组件的背景色 Component
setBackground(Color c)
4.设置组件默认前景色 Component
setForeground(Color c)
字体
AWT定义的五个逻辑字体名
SansSerif //无衬线字体(黑体)
Serif //有衬线字体(宋体)
Monospaced //等宽字体
Dialog //对话框字体
DialogInput //对话框输入字体
字体风格:
Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD+Font.ITALIC
获取系统可用字体的字符串数组
1.获取描述用户系统图形环境的对象
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
2.通过此对象获取系统所有可用字体家族名的字符串数组
String[] fontnames=ge.getAvailableFontFamilyNames();
创建字体对象
1.通过构造函数创建一个字体对象
Font myFont=new Font("SansSerif",Font.ITALIC,14);
2.载入一个TrueType字体或者Type 1字体,使用静态方法createFont()。
参数1是int类型指示字体类型是TrueType字体或者Type 1字体:Font.TRUETYPE_FONT/Font.TYPE1_FONT
参数2是字体载入源
static FontcreateFont(int fontFormat, File fontFile)
返回一个使用指定字体类型和指定字体文件的新 Font。
static Font createFont(int fontFormat, InputStream fontStream)
返回一个使用指定字体类型和输入数据的新 Font。
通过createFont()载入的字体默认是PLAIN风格,字体大小为1
需要调整属性则在创建后使用derive方法,这是重载的方法,参数为float时表示大小,int时表示风格
myFont.derive(float size);
myFont.derive(int style);
myFont.derive(int style,float size)
=====
自定义字体的创建未完待续
使用字体:
设置后绘制的文本都使用此字体 Graphics2D:
setFont(Font f)
setFont()方法多次使用,不论代码顺序,显示的文本的字体都是以最后一次setFont设置的字体显示,即使drawString语句在最后一次setFont语句之前。
获取使用某种字体的文本的相关位置和大小属性:
1.获取屏幕设备字体属性的描述对象Graphics2D:(render是渲染的意思)
返回这个图形文本中,指定字体特征的字体绘制环境:通常在使用前此组件的Graphics2D对象已经使用了setFont(),所以此方法返回的是指定为setFont设置的字体的绘制环境
FontRenderContext context=g2d.getFontRenderContext();//FontRenderContext位于java.awt.font.*;
2.获取包围使用某种字体的文本的矩形对象Font:
Rectangle2D rectBounds=myFont.getStringBounds(msg,context);
3.获取使用某种字体的文本的宽高上坡度
double msgW=rectBounds.getWidth();
double msgH=rectBounds.getHeight();
double ascent=-rectBounds.getY();//获取到的包围文本的矩形的x,y坐标是相对的,x=0,y=-ascent。
4.获取使用某种字体的文本的下坡度和行距
LineMetrics是测定字符串宽度的线性metrics对象,除了能获取下坡度和行距,还可以获取上坡度和总高度,返回值都是float单精度
LineMetrics metrics=myFont.getLineMetrics(msg,context);
float descent=metrics.getDescent();
float leading=metrics.getLeading();
float ascent=metrics.getAscent();
float msgH=metrics.getHeight();