自定义view的触摸点击区域

综合技术 2018-05-21

先看下实现效果

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;

    }
}

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

您可能感兴趣的

Android Developer Capstone Project: Building a Suc... Description This Project is about combining various skills you?ve attained through the MicroMasters Program. They include: Listing the services invo...
轻量级、无耦合、高灵活图片压缩类库... 起因 各位安卓开发的小伙伴,开发app或多或少都涉及到图片。我们的图片是那里来的呢?毫无疑问,第一次是从网络下载,之后才是用的缓存。 如果图片过于高清(资源大),我们下载展示出来就会很慢,这样用户体验肯定很差。那么,该怎么办呢?对的,下载尺寸更小的图片。不过,这些图片(头像,封面)等都是用户...
Mark!Android最佳的开源库集锦(实用) 工欲善其事,必先利其器。一个好的开发库可以快速提高开发者的工作效率,甚至让开发工作变得简单。本文收集了大量的Android开发库,快来切磋一下,到底哪一个最适合你。 动画 Android View Animations :一个非常强大的开源动画库,开发者可以用来创建各...
Kivy pyjnius with Buildozer – Adding jnius t... after adding these lines of code to my kivy app, when i start it on my android 4.4.4 the app immediately crashes from jnius import autoclass try: ...
MVPFrame for Android 你值得拥有的二次封装MVP架构基类库... MVPFrame MVPFrame for Android 是一个集合了 Retrofit2 + RXJava2 + Mosby3 二次封装的MVP架构基类库,方便敏捷开发,后续会持续更新并完善。 Gif 展示 引入 Maven: com.king.frame ...