在android 中需要通过graphics类来显示2D图形,graphics中包括了Canvas 画布,Paint 画笔,Color 颜色 ,Bitmap 图像,2D几何图像等常用类。
这个类也是继承View ,相当于自己定义一个View类,在别的activity中创建并引用它;
private Paint paint;
public PaintAndColor(Context context) {
super(context);
// TODO Auto-generated constructor stub
paint = new Paint();
new Thread(this).start();
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
paint.setAntiAlias(true);//设置paint为无锯齿
paint.setColor(Color.GREEN);//设置画笔的颜色
// paint.setColor(Color.rgb(255, 0, 0));
paint.setTextSize(14);//设置字体尺寸
paint.setAlpha(220);//设置Alpha的值
paint.setStyle(Paint.Style.STROKE);//设置paint的风格为空心,当然也可以为实心(Paint.Style.FILL)
paint.setStrokeWidth(5);//设置空心的外框的宽度
//当然上面设置的属性,paint也有相应的方法来取得
/* paint.getColor();
paint.getAlpha();
paint.getTextSize();
paint.getStyle();
paint.getStrokeWidth();*/
canvas.drawRect(120, 100, 120, 60, paint);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawCircle(70, 70, 50, paint);
}
@Override
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().interrupted()) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Thread.currentThread().interrupt();
}
postInvalidate();
}
}
}