自定义View圆圈跟随手指的demo

package com.example.a03_customview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by yujie on 2017/11/30.
 */

public class DrawView extends View{
    public DrawView(Context context) {
        super(context);
    }

    public DrawView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private int cx = 100;
    private int cy = 100;
    /**
     * Canvas canvas画布.....paint画笔
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //中心点x坐标,y坐标,半径,画笔
        Paint paint = new Paint();
        paint.setColor(Color.RED);//设置颜色

        paint.setStrokeWidth(2);//描边的宽度2个像素
        //Paint.Style.FILL填充,,Paint.Style.STROKE描边 ,,Paint.Style.FILL_AND_STROKE填充并且描边
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);//设置抗锯齿

        canvas.drawCircle(cx,cy,100,paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                cx = (int) event.getX();
                cy = (int) event.getY();

                break;
            case MotionEvent.ACTION_MOVE:
                cx = (int) event.getX();
                cy = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                cx = (int) event.getX();
                cy = (int) event.getY();
                break;
        }

        //重新绘制....自动去调用onDraw
        postInvalidate();//.........可以使用在子线程
        //invalidate();//...只能用在主线程

        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值