Android高级进阶——绘图篇(一)Canvas基本操作

本文详细介绍了Android中Canvas的基本操作,包括画圆、矩形、圆角矩形、椭圆、圆弧、直线及多条直线。Canvas与Paint作为Android图形绘制的核心工具,通过设置Paint属性和调用Canvas的各种draw方法,可以实现丰富的图形绘制效果。
摘要由CSDN通过智能技术生成

开篇

前面在介绍 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-autoxmlns: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:圆的半径
-

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值