美文网首页Android开发经验谈
自定义view的触摸点击区域

自定义view的触摸点击区域

作者: 苏苏苏苏考拉 | 来源:发表于2018-05-18 12:42 被阅读44次

    先看下实现效果


    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;
    
        }
    }
    

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

    相关文章

      网友评论

        本文标题:自定义view的触摸点击区域

        本文链接:https://www.haomeiwen.com/subject/tnhgdftx.html