开篇
前面在介绍 onDraw 过程时,有提到 View 的绘制(Canvas 的使用),后续的几篇会详细的介绍有关 Canvas 以及 Paint 的相关操作。
Canvas 和 Paint
Canvas 和 Paint 之间的关系就像我们平时画画需要的画笔和画纸一样,我们画画无外乎也就需要这两个工具,而这两个工具体现在 Android 中,就是我们的 Paint(画笔)和 Canvas(画纸,通常称为画布),所以凡是跟要画的东西设置相关的,比如颜色、大小、宽度、样式、透明度等都是在 Paint 中设置的。而凡是跟要画的成品,比如想画一个矩形、圆形、文字、路径等都是通过 Canvas 操作的。
Canvas 的基本操作
- 新建一个类,派生自 View,重写 View 的 onDraw 方法,在 onDraw 方法中通过 Canvas 来实现我们想要实现的效果:
public class CustomView extends View {
private Paint paint;
public CustomView(Context context) {
super(context);
init();
}
private void init() {
//初始化画笔
paint = new Paint();
//设置抗锯齿
paint.setAntiAlias(true);
//设置画笔宽度
paint.setStrokeWidth(5);
//设置画笔颜色
paint.setColor(Color.RED);
//设置画笔样式
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
- 然后在布局文件中使用我们的自定义View:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android”
xmlns:app="http://schemas.android.com/apk/res-auto”
xmlns:tools="http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”
tools:context=“com.example.hecom.annotationlibrary.MainActivity”>
<com.example.hecom.annotationlibrary.CustomView
android:layout_width=“match_parent”
android:layout_height="match_parent” />
</LinearLayout>
- 画就行了
1、使用 Canvas 画圆
void drawCircle (float cx, float cy, float radius, Paint paint)
参数:
- cx:圆心点的 X 轴坐标
- cy:圆心点的 Y 轴坐标
- radius:圆的半径
-