android自定义view之实现三角尺功能

0.前言

小编好久没写博客了,由于业务需要这几天遇到了一个难题困扰了小编很久,最后还是解决了,觉得有必要写一下。没错,就是实现三角板的功能,而且还是可移动的哦。

1.需求分析

实现一个可移动的三角尺,要求可以根据需要旋转并且能够当作作图工具进行作图。由于要求可移动并且能当作工具使用,也就是说三角板的view需要位于作图view的上层,因此可以使用PopupWindow实现;由于三角板是三角图形的,非矩形,而我们知道android的控件是矩形的,因此必须解决事件处理的问题。
话不多说,直接上代码吧

1.PopupWindow

首先是实现PopupWindow:
父类

protected PopupWindow window;
protected View view;
public void createTRiangleWindow(int width,int height)
    {
        this.width=width;this.height=height;
        assControls();
        setOnClickListen();
        createTriangleWindow(width,height);
    }

 public void showTriangleWindow(int x,int y)
    {
        px = x;
        py = y;//如果需要打开二级菜单,在同个位置打开;
        setType();
        window.showAtLocation(theApp.getDrawManager().getDrawArea(), Gravity.LEFT | Gravity.TOP,px,py);
    }

父类维护了一个PopuWindow
接下来是子类具体实现:

package com.donview.board.ui.PopupWindow


class TriangleProtratorWindow(val con: Context) : PopupWindowEx(con) {
    private var rl_parent:RelativeLayout?=null
    private var iv_ball_top:ImageView?=null
    private var iv_ball_bottom_left:ImageView?=null
    private var iv_ball_bottom_right:ImageView?=null
    protected var lastX: Int = 0
    protected var lastY: Int = 0
    private var oriLeft: Int = 0
    private var oriRight:Int = 0
    private var oriTop:Int = 0
    private var oriBottom:Int = 0
    //初始的旋转角度
    private var oriRotation = 0f
    private val TAG="TrianglePrint"
    private var ib_triangle: ImageView?=null
    val points= ArrayList<Point>()
    private var screenWidth=0
    private var screenHeight=0
    private var density: Float?=null
    private var singlePointId: Int = 0

//代码块1
    override fun assControls() {
        view = LayoutInflater.from(theApp).inflate(R.layout.triangle_layout, null)
        ib_triangle=view!!.findViewById(R.id.ib_triangle)
        rl_parent=view!!.findViewById(R.id.rl_parent)
        iv_ball_top=view!!.findViewById(R.id.iv_ball_top)
        iv_ball_bottom_left=view!!.findViewById(R.id.iv_ball_bottom_left)
        iv_ball_bottom_right=view!!.findViewById(R.id.iv_ball_bottom_right)
        val mWindowManager = theApp.getApplicationContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val mDisplay = mWindowManager.getDefaultDisplay()
        val mDisplayMetrics = DisplayMetrics()
        mDisplay.getRealMetrics(mDisplayMetrics)
        density = mDisplayMetrics.density
        screenWidth = if (density!!.toDouble() == 1.5) DEFAULT_4K_SCREEN_WIDTH else mDisplayMetrics.widthPixels
        screenHeight = if (density!!.toDouble() == 1.5) DEFAULT_4K_SCREEN_HEIGHT else mDisplayMetrics.heightPixels
    }

//设置触摸事件
    override fun setOnClickListen() {
        view!!.setOnTouchListener(MyOnTouchListener())//为整个view点击触摸事件
    }

    private var isResolve=true
//代码3
    inner class MyOnTouchListener : View.OnTouchListener {
        var orgX: Int = 0
        var orgY:Int = 0
        override fun onTouch(v: View, event: MotionEvent): Boolean {
            val action = event.action and MotionEvent.ACTION_MASK
            //获取控件在屏幕的位置
            val location =  IntArray(2);
            view!!.getLocationOnScreen(location);
            //控件相对于屏幕的x与y坐标
            val xL = location[0];
            val yL = location[1];
            val xEvent = event.x//落脚点坐标
            val yEvent = event.y
            val screenX=xEvent+xL
            val screenY=yEvent+yL
            val point=Point(screenX.toDouble(),screenY.toDouble())
            val inside=isInside(point)
          
            if (action == MotionEvent.ACTION_DOWN) {
                oriLeft = v.left
                oriRight = v.right
                oriTop = v.top
                oriBottom = v.bottom
                lastY = event.rawY.toInt()
                lastX = event.rawX.toInt()
                oriRotation = v.rotation
                Log.d(TAG, "ACTION_DOWN: $oriRotation")
            }
            if (show)delDrag(rl_parent!!, event, action)
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    if (inside){
//点击的是三角图形内部
//记录落点位置,用于实现移动
                        orgX = event.getX().toInt()
                        orgY = event.getY().toInt()
                        isResolve=false//内部点击不需要处理绘画事件
                    }else{
                        isResolve=true
                    }
                    if (isResolve){
                       //省略业务代码,主要是进行图形绘制
                    }
                    LogUit.printD("TouchPrint", "按下")
                }
                MotionEvent.ACTION_POINTER_DOWN->{
                    if (isResolve){
                        //省略业务代码,主要是进行图形绘制
                    }
                }
                MotionEvent.ACTION_MOVE->{
                    if (isResolve){
                        //省略业务代码,主要是进行图形绘制
                        
                    }else{
                        offsetX = event.getRawX().toInt() - orgX
                        offsetY = event.getRawY().toInt() - orgY
//实现随手指移动窗口
                        window.update(offsetX, offsetY, if (width == 0) ViewGroup.LayoutParams.WRAP_CONTENT else width,
                                if (height == 0) ViewGroup.LayoutParams.WRAP_CONTENT else height, true)
                    }
                }
                MotionEvent.ACTION_POINTER_UP->{
                    if (isResolve){
                        //省略业务代码,主要是进行图形绘制
                  }
                }
                MotionEvent.ACTION_UP -> {
                    if (isResolve){
                        //省略业务代码,主要是进行图形绘制
                    }
                    else if (inside){
                        showOrHide()//显示和隐藏顶点
                    }
                    
            }
           
            return true
        }

    }

    private var show=false
//显示和隐藏三个顶点
    private fun showOrHide() {
        show=!show
        iv_ball_top!!.visibility=if (show) View.VISIBLE else View.INVISIBLE
        iv_ball_bottom_left!!.visibility=if (show) View.VISIBLE else View.INVISIBLE
        iv_ball_bottom_right!!.visibility=if (show) View.VISIBLE else View.INVISIBLE
    }

//判断落点是否位于三个顶点所围成的三角形内部
    private fun isInside(point: Point): Boolean {
        val location1 =  IntArray(2);
        iv_ball_top!!.getLocationOnScreen(location1);
        //控件相对于屏幕的x与y坐标
        val xL1 = location1[0];
        val yL1 = location1[1];

        val location2 =  IntArray(2);
        iv_ball_bottom_left!!.getLocationOnScreen(location2);
        //控件相对于屏幕的x与y坐标
        val xL2 = location2[0];
        val yL2 = location2[1];

        val location3 =  IntArray(2);
        iv_ball_bottom_right!!.getLocationOnScreen(location3);
        //控件相对于屏幕的x与y坐标
        val xL3 = location3[0];
        val yL3 = location3[1];
   
        points.clear()
        points.add(Point(xL1.toDouble(),yL1.toDouble()))
        points.add(Point(xL2.toDouble(),yL2.toDouble()))
        points.add(Point(xL3.toDouble(),yL3.toDouble()))
        return isPolygonContainsPoint(points,point)
    }

//判断点point是否落在集合mPoints围成的多边形内
 public boolean isPolygonContainsPoint(List<Point> mPoints, Point point) {
        int nCross = 0;
        for (int i = 0; i < mPoints.size(); i++) {
            Point p1 = mPoints.get(i);
            Point p2 = mPoints.get((i + 1) % mPoints.size());
            // 取多边形任意一个边,做点point的水平延长线,求解与当前边的交点个数
            // p1p2是水平线段,要么没有交点,要么有无限个交点
            if (p1.getY() == p2.getY())
                continue;
            // point 在p1p2 底部 --> 无交点
            if (point.getY() < Math.min(p1.getY(), p2.getY()))
                continue;
            // point 在p1p2 顶部 --> 无交点
            if (point.getY() >= Math.max(p1.getY(), p2.getY()))
                continue;
            // 求解 point点水平线与当前p1p2边的交点的 X 坐标
            double x = (point.getY() - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()) + p1.getX();
            if (x > point.getX()) // 当x=point.x时,说明point在p1p2线段上
                nCross++; // 只统计单边交点
        }
        // 单边交点为偶数,点在多边形之外 ---
        return (nCross % 2 == 1);
    }

  //获取旋转角,旋转view
    private fun delDrag(v: View, event: MotionEvent, action: Int) {
        when (action) {
            MotionEvent.ACTION_MOVE -> {
                val dx = event.rawX.toInt() - lastX
                val dy = event.rawY.toInt() - lastY
                val center = android.graphics.Point(oriLeft + (oriRight - oriLeft) / 2, oriTop + (oriBottom - oriTop) / 2)
                val first = android.graphics.Point(lastX, lastY)
                val second = android.graphics.Point(event.rawX.toInt(), event.rawY.toInt())
                oriRotation += angle(center, first, second)

                v.rotation = oriRotation
                lastX = event.rawX.toInt()
                lastY = event.rawY.toInt()
                Log.i(TAG, "ACTION_MOVE")
            }
        }
    }

    fun angle(cen: android.graphics.Point, first: android.graphics.Point, second: android.graphics.Point): Float {
        val dx1: Float
        val dx2: Float
        val dy1: Float
        val dy2: Float

        dx1 = (first.x - cen.x).toFloat()
        dy1 = (first.y - cen.y).toFloat()
        dx2 = (second.x - cen.x).toFloat()
        dy2 = (second.y - cen.y).toFloat()

        // 计算三边的平方
        val ab2 = ((second.x - first.x) * (second.x - first.x) + (second.y - first.y) * (second.y - first.y)).toFloat()
        val oa2 = dx1 * dx1 + dy1 * dy1
        val ob2 = dx2 * dx2 + dy2 * dy2

        // 根据两向量的叉乘来判断顺逆时针
        val isClockwise = (first.x - cen.x) * (second.y - cen.y) - (first.y - cen.y) * (second.x - cen.x) > 0

        // 根据余弦定理计算旋转角的余弦值
        var cosDegree = (oa2 + ob2 - ab2) / (2.0 * Math.sqrt(oa2.toDouble()) * Math.sqrt(ob2.toDouble()))

        // 异常处理,因为算出来会有误差绝对值可能会超过一,所以需要处理一下
        if (cosDegree > 1) {
            cosDegree = 1.0
        } else if (cosDegree < -1) {
            cosDegree = -1.0
        }

        // 计算弧度
        val radian = Math.acos(cosDegree)

        // 计算旋转过的角度,顺时针为正,逆时针为负
        return (if (isClockwise) Math.toDegrees(radian) else -Math.toDegrees(radian)).toFloat()

    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/rl_parent"
        android:layout_marginTop="70dp"
        android:layout_marginBottom="70dp"
        android:layout_marginStart="100dp"
        android:layout_marginEnd="100dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/ib_triangle"
            android:src="@drawable/trangle_contain_protractor"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </ImageView>
        <ImageView
            android:visibility="invisible"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="50dp"
            android:background="@android:color/white"
            android:id="@+id/iv_ball_top"
            android:layout_width="10dp"
            android:layout_height="10dp" />
        <ImageView
            android:visibility="invisible"
            android:layout_alignParentBottom="true"
            android:background="@android:color/white"
            android:id="@+id/iv_ball_bottom_left"
            android:layout_marginBottom="50dp"
            android:layout_width="10dp"
            android:layout_height="10dp" />
        <ImageView
            android:visibility="invisible"
            android:layout_marginBottom="50dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:background="@android:color/white"
            android:id="@+id/iv_ball_bottom_right"
            android:layout_width="10dp"
            android:layout_height="10dp" />
    </RelativeLayout>

</RelativeLayout>

Point类如下:

public class Point {
    private double x;//X坐标
    private double y;//y坐标

    public Point(double x,double y){
        setX(x);
        setY(y);
    }

    public double getY() {
        return y;
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public void setY(double y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "x="+x+",y="+y;
    }
}

ok,代码就先贴在这里了,接下来就是分析了
代码有点多,接下来就根据各项需求来进行分析吧

  • 随手势移动
    首先是实现手势移动。实现手势移动的功能很简单,只需要在事件
    ACTION_DOWN时获取落脚点的位置:
                     orgX = event.getX().toInt()
                       orgY = event.getY().toInt()

然后在移动的时候获取位置差计算出距离即可:

 offsetX = event.getRawX().toInt() - orgX
                        offsetY = event.getRawY().toInt() - orgY

然后再刷新当前window的位置就可以了

window.update(offsetX, offsetY, if (width == 0) ViewGroup.LayoutParams.WRAP_CONTENT else width,
                                if (height == 0) ViewGroup.LayoutParams.WRAP_CONTENT else height, true)
  • 三角尺的控件
    这是个难点。为什么说时难点呢?因为我们知道安卓的控件是矩形的,就算你吧他的背景图片设置成其他图形的,他仍然是矩形控件,小编一开始采取的方法是自定义控件,最后以失败告终。最后终于在网上的几篇博客上受到启发:竟然无法实现三角形控件,那我们能不能做到只对三角图形内部的区域响应事件呢?这样就可以达到欺骗用户的效果。说做就做。
    由此引发了几个问题如下:
  • 1.首先我们需要确定落点是否在多边形内部
  • 2.旋转图形后,必须保证仍然可以正确确定落点是否在多边形内部
    首先是确定落点是否在多边形内部的问题,这个在网上可以找方法,这里小编就直接引用网上的方法了:
 /**
     * 返回一个点是否在一个多边形区域内
     *
     * @param mPoints 多边形坐标点列表
     * @param point   待判断点
     * @return true 多边形包含这个点,false 多边形未包含这个点。
     */
    public static boolean isPolygonContainsPoint(List<Point> mPoints, Point point) {
        int nCross = 0;
        for (int i = 0; i < mPoints.size(); i++) {
            Point p1 = mPoints.get(i);
            Point p2 = mPoints.get((i + 1) % mPoints.size());
            // 取多边形任意一个边,做点point的水平延长线,求解与当前边的交点个数
            // p1p2是水平线段,要么没有交点,要么有无限个交点
            if (p1.getY() == p2.getY())
                continue;
            // point 在p1p2 底部 --> 无交点
            if (point.getY() < Math.min(p1.getY(), p2.getY()))
                continue;
            // point 在p1p2 顶部 --> 无交点
            if (point.getY() >= Math.max(p1.getY(), p2.getY()))
                continue;
            // 求解 point点水平线与当前p1p2边的交点的 X 坐标
            double x = (point.getY() - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()) + p1.getX();
            if (x > point.getX()) // 当x=point.x时,说明point在p1p2线段上
                nCross++; // 只统计单边交点
        }
        // 单边交点为偶数,点在多边形之外 ---
        return (nCross % 2 == 1);
    }

传入多边形的顶点的集合和落脚点即可。
由于业务需要,小编这里必须计算当前点在整个屏幕的位置,计算方法也很简单,即点击点的坐标+控件相对于屏幕的位置即可。具体看代码。
接下来是第二个问题,首先是实现旋转的功能,具体方法如下(从网上找到的方法):
首先是在按下时获取当前view的位置:

 oriLeft = v.left
                oriRight = v.right
                oriTop = v.top
                oriBottom = v.bottom
                lastY = event.rawY.toInt()
                lastX = event.rawX.toInt()
                oriRotation = v.rotation

记录上一个点的坐标是为了计算两点直接的角度
然后在移动的时候计算角度:

val dx = event.rawX.toInt() - lastX
                val dy = event.rawY.toInt() - lastY//Y轴上移动的位置
                val center = android.graphics.Point(oriLeft + (oriRight - oriLeft) / 2, oriTop + (oriBottom - oriTop) / 2)//获取中心点
                val first = android.graphics.Point(lastX, lastY)//第一个点
                val second = android.graphics.Point(event.rawX.toInt(), event.rawY.toInt())//第二个点
                oriRotation += angle(center, first, second)//传递三个点计算出夹角,额,这里是oriRotation

                v.rotation = oriRotation
                lastX = event.rawX.toInt()
                lastY = event.rawY.toInt()
                Log.i(TAG, "ACTION_MOVE")

然后再将view的rotation 设置为计算得到的rotation就行了。
必须说明的是,这里小编使用了三个小控件分别位于三角形的顶点,主要是为了确定三角形的顶点位置从而正确计算出落脚点是否再三角形内部,然后在旋转图形的时候将三角图形与这些点一起旋转即可。
最后再贴上具体调用的代码:

 //三角尺
    private fun showTriangle(){
        if(triangleProtratorWindow!=null) triangleProtratorWindow!!.shutdown()
        triangleProtratorWindow=TriangleProtratorWindow(theApp!!)
        triangleProtratorWindow!!.createTRiangleWindow(DEFAULT_TRIANGLE_WIDTH, DEFAULT_TRIANGLE_HEIGHT)
        triangleProtratorWindow!!.showTriangleWindow(200, 200)
    }

再附上效果图:


Screenshot_2020-03-06-01-16-30-607_com.miui.home.png
Screenshot_2020-03-06-01-16-39-048_com.miui.home.png

本文代码有点多,基础不好的小白可能需要多读几遍然后学以致用(大佬请略过~)
本文只给出思路和本人的具体实现方法,由于时间仓促,就不写那么多了,有问题欢迎留言,谢谢大家

[原创文章,转载请附上]https://www.jianshu.com/p/8daa4457a77b

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

推荐阅读更多精彩内容

  • 为什么选择自定义View来做起头?可能是因为我最有成就感的事情除了大一刚接触编程时就进入了ACM之外,就是...
    孤独的伤逝阅读 727评论 1 5
  • 参考:https://www.w3cplus.com/svg/svg-fill-features.htmlhttp...
    天煞魔猎手阅读 2,439评论 1 3
  • 目标: 1、掌握自定义view的流程2、掌握自定义view的三个方法3、掌握自定义view实现方式4、掌握自定义v...
    小慧sir阅读 119评论 0 0
  • 目标: 1、掌握自定义view的流程2、掌握自定义view的三个方法3、掌握自定义view实现方式4、掌握自定义v...
    Anwfly阅读 1,724评论 2 7
  • 目标: 1、掌握自定义view的流程2、掌握自定义view的三个方法3、掌握自定义view实现方式4、掌握自定义v...
    烟刺痛了眼_a1b7阅读 371评论 0 0