自定义view的触摸点击区域

先看下实现效果


device-2018-05-18-111253.gif

对于自定义view不规则区域的触摸事件点击响应涉及的知识点
1.Region
2.Matrix坐标系变换
拓展知识点:3.Path绘图

Region

Region是绘制中的区域,是一个闭合的区域。使用Region可以取区域的交集或者并集最后得到我们的不规则区域。
Region的构造方法有

public Region()  
public Region(Region region) 
public Region(Rect r)  
public Region(int left, int top, int right, int bottom) 

Region也可以后期添加区域

public void setEmpty()  //清空
public boolean set(Region region)   
public boolean set(Rect r)   
public boolean set(int left, int top, int right, int bottom)   
public boolean setPath(Path path, Region clip)//将path和clip的两个区域取交集

对于上述的不规则区域,我们可以取一张屏幕画布和该不规则区域的path取交集,这样就能得到我们想要获得的区域了。

circleRegion = new Region();
path = new Path();
//Path.Direction.CW---顺时针  Path.Direction.CCW逆时针
path.addCircle(width / 2, height / 2, 250, Path.Direction.CW);

Region region = new Region(0, 0, width, height);
circleRegion.setPath(path, region);

可以使用

//绘制
RegionIterator iterator = new RegionIterator(region);
Rect rect = new Rect();
while (iterator.next(rect)) {
    canvas.drawRect(rect, mPaint);
}

遍历我们得到的region区域。
知道了region概念后,我们可以对一个圆形图案的触摸坐标判断是否在圆形区域内。

image.png
public class AbsoluteMap extends View {

    private Paint paint;
    private int width, height;
    private Path path;
    private Region circleRegion;

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

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLUE);
        paint.setStrokeWidth(10);


        circleRegion = new Region();
        path = new Path();
        //Path.Direction.CW---顺时针  Path.Direction.CCW逆时针
        path.addCircle(width / 2, height / 2, 250, Path.Direction.CW);

        Region region = new Region(0, 0, width, height);
        circleRegion.setPath(path, region);

    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        init();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(width / 2, height / 2, 250, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (circleRegion.contains((int) event.getX(), (int) event.getY())) {
                    Toast.makeText(getContext(), "触摸区域内", Toast.LENGTH_LONG).show();
                }
                break;
        }
        return true;

    }
}

可以看到,我们取出圆形region后,再对用户的触摸坐标getx,gety判断是否在区域内即可。

2.Matrix

image.png

从第一个例子可以看到我们用的是相对坐标系getx,gety来确定用户的触摸区域的,这样就存在一个问题,有时候开发者为了方便或者绘制的图形是对称图形时,我们会将坐标系平移,做出变换,这时候getx,gety就会发生变化。
所以一般我们会使用getRawX,getRawY来获取用户坐标,但是怎么把用户的绝对坐标转换成我们的画布坐标呢?
这里就需要了解一下Matrix了。


image.png

mapPoints mapRect mapVectors
这些API主要是根据当前Matrix矩阵对点、矩形区域和向量进行变换,以得到变换后的点、矩形区域和向量。经常和下面的invert方法结合使用。

invert
通过上面的mapXXX方法,可以获取变换后的坐标或者矩形。但假设我们知道了变换后的坐标,如何计算Matrix变换前的坐标那?!
此时通过invert方法获取的逆矩阵就派上用场了。所谓逆矩阵,就是Matrix旋转了30度,逆Matrix就反向旋转30度,Matrix放大n倍,逆Matrix就缩小n倍。

public class ChangeMap extends View {


    private Paint paint;
    private int width, height;
    private Path path;
    private Region circleRegion;
    private Matrix matrix;

    private float[] touchPoints = new float[2];

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

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLUE);
        paint.setStrokeWidth(10);


        circleRegion = new Region();
        path = new Path();
        //Path.Direction.CW---顺时针  Path.Direction.CCW逆时针
        path.addCircle(0, 0, 250, Path.Direction.CW);

        Region region = new Region(-width / 2, -height / 2, width / 2, height / 2);
        circleRegion.setPath(path, region);

        matrix = new Matrix();

    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        init();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(width / 2, height / 2);
        matrix.reset();
        if (matrix.isIdentity()) {
            canvas.getMatrix().invert(matrix);
        }
        canvas.drawPath(path, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                touchPoints[0] = event.getRawX();
                touchPoints[1] = event.getRawY();

                matrix.mapPoints(touchPoints);
                if (circleRegion.contains((int) touchPoints[0], (int) touchPoints[1])) {
                    Toast.makeText(getContext(), "触摸区域内", Toast.LENGTH_LONG).show();
                }
                break;
        }
        return true;

    }
}

明白了基本原理以后,我们就可以对复杂的不规则区域进行点击事件的判断了。
绘制第一张的图时,主要用到的就是path工具类。

public class SpecialMap extends View {
    private Paint paint;
    private int width, height;
    private Region topRegion, leftRegion, rightRegion, bottomRegion, totalRegion, centerRegion;
    private Matrix matrix;
    private RectF rectFBig, rectFSmall;
    private Path leftPath, topPath, rightPath, bottomPath, centerPath;

    private float[] touchPoints = new float[2];

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

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.LTGRAY);
        paint.setStrokeWidth(10);

        topRegion = new Region();
        leftRegion = new Region();
        rightRegion = new Region();
        bottomRegion = new Region();
        totalRegion = new Region();
        centerRegion = new Region();

        rectFBig = new RectF(-400, -400, 400, 400);
        rectFSmall = new RectF(-250, -250, 250, 250);
        totalRegion = new Region(-width / 2, -height / 2, width / 2, height / 2);

        leftPath = new Path();
        topPath = new Path();
        rightPath = new Path();
        bottomPath = new Path();
        centerPath = new Path();

        int sweepAngle = 80;
        /**
         * startAngle是开始度数
         * sweepAngle指的是旋转的度数,也就是以startAngle开始,旋转多少度,如果sweepAngle是正数,那么就是按顺时针方向旋转,如果是负数就是按逆时针方向旋转。
         */
        rightPath.addArc(rectFBig, 5, sweepAngle);
        /**
         * arcTo是先画一个椭圆,然后再在这个椭圆上面截取一部分部形。这个图形自然就是一个弧线了
         */
        rightPath.arcTo(rectFSmall, 5 + sweepAngle, -sweepAngle);
        rightPath.close();

        bottomPath.addArc(rectFBig, 95, sweepAngle);
        bottomPath.arcTo(rectFSmall, 95 + sweepAngle, -sweepAngle);
        bottomPath.close();


        leftPath.addArc(rectFBig, 185, sweepAngle);
        leftPath.arcTo(rectFSmall, 185 + sweepAngle, -sweepAngle);
        leftPath.close();


        topPath.addArc(rectFBig, 275, sweepAngle);
        topPath.arcTo(rectFSmall, 275 + sweepAngle, -sweepAngle);
        topPath.close();

        centerPath.addCircle(0, 0, 120, Path.Direction.CW);
        matrix = new Matrix();

        leftRegion.setPath(leftPath, totalRegion);
        topRegion.setPath(topPath, totalRegion);
        rightRegion.setPath(rightPath, totalRegion);
        bottomRegion.setPath(bottomPath, totalRegion);
        centerRegion.setPath(centerPath, totalRegion);


    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        init();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(width / 2, height / 2);
        matrix.reset();
        if (matrix.isIdentity()) {
            canvas.getMatrix().invert(matrix);
        }
        canvas.drawPath(leftPath, paint);
        canvas.drawPath(bottomPath, paint);
        canvas.drawPath(rightPath, paint);
        canvas.drawPath(topPath, paint);
        canvas.drawPath(centerPath, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                touchPoints[0] = event.getRawX();
                touchPoints[1] = event.getRawY();

                matrix.mapPoints(touchPoints);
                if (topRegion.contains((int) touchPoints[0], (int) touchPoints[1])) {
                    Toast.makeText(getContext(), "点击了右上部", Toast.LENGTH_LONG).show();
                } else if (leftRegion.contains((int) touchPoints[0], (int) touchPoints[1])) {
                    Toast.makeText(getContext(), "点击了左上部", Toast.LENGTH_LONG).show();
                } else if (bottomRegion.contains((int) touchPoints[0], (int) touchPoints[1])) {
                    Toast.makeText(getContext(), "点击了左下部", Toast.LENGTH_LONG).show();
                } else if (rightRegion.contains((int) touchPoints[0], (int) touchPoints[1])) {
                    Toast.makeText(getContext(), "点击了右下部", Toast.LENGTH_LONG).show();
                } else if (centerRegion.contains((int) touchPoints[0], (int) touchPoints[1])) {
                    Toast.makeText(getContext(), "点击了中部", Toast.LENGTH_LONG).show();
                }
                break;
        }
        return true;

    }
}

注:可能需要关闭硬件加速

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容