1.颜色对象
Color
Android系统当中颜色的表示方法:
1.int color1 = Color.blue;
2.int color2 = Color.argb(177, 255, 255, 255);
3.在XML文件当中定义颜色
2.画笔对象
Paint
该类的对象用于控制画笔的风格和颜色等方面的信息
paint.setColor(Color.blue);
3.画布对象
该类代表着一块“画布”,可以在上面绘制字符、图形和图片等内容
canvas.drawCircle(300, 400, 100, paint);
自定义View的基本实现方法
1.定义一个类,继承View
2.复写View的onDraw函数
3.在onDraw当中使用Canvas和Paint对象绘制图形
Android坐标系:左上角为原点(向右向下为正方向)
画一条线
public class MyView extends View {
public MyView(Context context) {
super(context);
}
//当Android系统需要绘制一个View对象时,
//就会调用该对象的onDraw方法
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawLine(0, 0, 200, 200, paint);
super.onDraw(canvas);
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
setContentView(new MyView(this));
}
}
1.Paint的设置方法
setAntiAlias:设置画笔的锯齿效果
setStrokeWidth:设置空心的边框宽度
setStyle:设置画笔风格,空心或者实心
setARGB
setTextSize
setColor
setAlpha
getColor
getAlpha
2.使用Canvas绘制点、线和图形
绘制直线:
drawLine(float startX, float startY, float stopX, float stopY, Paint paint)
绘制矩形:
drawRect(float left, float top, float right, float bottom, Paint paint)
绘制圆形:
drawCircle(float cx, float cy, float radius, Paint paint)
3.使用Canvas绘制文字
使用Canvas绘制字符
drawText(String text, float x, float y, Paint paint)
y轴坐标并不是底部非坐标,而是基于基准线(并不是字符串的底部,比如是a的底部但不是p的底部等)
4使用Canvas绘制图片的方法
drawBitmap(Bitmap bitmap, float left, float top, Paint paint):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
MyView myView = new MyView(this);
setContentView(myView);
}
}
public class MyView extends View {
public MyView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setARGB(150, 0, 100, 200);
//设置画笔风格为空心(默认为实心)
// paint.setStyle(Paint.Style.STROKE);
// paint.setStyle(Paint.Style.FILL);
//设置空心的边框宽度
paint.setStrokeWidth(10);
paint.setTextSize(100);
canvas.drawText("apple", 50, 200, paint);
canvas.drawLine(0, 200, 500, 200, paint);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), 100, 300, paint);
// canvas.drawRect(100, 300, 300, 500, paint);
// canvas.drawCircle(200, 200, 150, paint);
super.onDraw(canvas);
}
}