自定义view实现网格拖曳效果

自定义view,类似ps中的曲线调节功能,忘了截图,以下源码。


public class GridDragView extends View {
    private int dp_4;//4dp
    private int width;//view宽度,设置width = height
    private int line_length;//绘制区域大小
    private int line_weight_light;//细线
    private int line_weight_bold;//粗线
    private Paint mPaint;//画主要部分
    private PointF left_top, right_top, left_bottom, right_bottom;//view顶点
    private int radius;//小圆圈半径
    private float line_gap;//网格距离
    private DashPathEffect dashPathEffect;//绘制虚线
    private PointF controlPoint;//控制点,即手指按下部位

    private Paint beislPaint;//绘制曲线
    private Path mPath;

    private int textSize;
    private String text_coordinate = "";


    public GridDragView(Context context) {
        this(context, null);
    }

    public GridDragView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    private void init(Context context) {
        DensityUtils densityUtils = new DensityUtils();//工具类,获取屏幕参数,dp2px等
//        screenWidth = mDensityUtils.getScreenWidth(context);
        line_weight_bold = densityUtils.dip2px(context, 2);
        line_weight_light = densityUtils.dip2px(context, 1);
        radius = densityUtils.dip2px(context, 7);
        dp_4 = densityUtils.dip2px(context, 4);
        textSize = densityUtils.dip2px(context, 12);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(Color.WHITE);
        mPaint.setStrokeWidth(line_weight_bold);


        beislPaint = new Paint();
        beislPaint.setAntiAlias(true);
        beislPaint.setDither(true);
        beislPaint.setColor(Color.WHITE);
        beislPaint.setStrokeWidth(line_weight_bold);
        beislPaint.setStyle(Paint.Style.STROKE);

        left_top = new PointF();
        left_bottom = new PointF();
        right_bottom = new PointF();
        right_top = new PointF();
        dashPathEffect = new DashPathEffect(new float[]{16, 8}, 0);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        controlPoint = new PointF();
        mPath = new Path();
    }

    private static final String TAG = "GridDragView";

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "onMeasure: width" + width);
        }
        line_length = (int) (width * 0.95);//设置绘制区域是view大小的95%,不充满
        //初始化坐标
        line_gap = line_length / 4f;
        left_top.set((width - line_length) / 2f, (width - line_length) / 2f);
        right_top.set((width + line_length) / 2f, (width - line_length) / 2f);
        left_bottom.set((width - line_length) / 2f, (width + line_length) / 2f);
        right_bottom.set((width + line_length) / 2f, (width + line_length) / 2f);
        if (BuildConfig.DEBUG){
            Log.e(TAG, "onMeasure: ltx:"+left_top.x+"  lty:"+left_top.y+"  rbx:"+right_bottom.x+"  rby:"+right_bottom.y);
        }
        //初始化控制点
        controlPoint.set(width / 2f, width / 2f);
        setMeasuredDimension(width, width);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画外轮廓
        mPaint.setStyle(Paint.Style.STROKE);
        canvas.drawLine(left_top.x, left_top.y, right_top.x, right_top.y, mPaint);
        canvas.drawLine(right_top.x, right_top.y, right_bottom.x, right_bottom.y, mPaint);
        canvas.drawLine(right_bottom.x, right_bottom.y, left_bottom.x, left_bottom.y, mPaint);
        canvas.drawLine(left_bottom.x, left_bottom.y, left_top.x, left_top.y, mPaint);
        canvas.drawCircle(right_top.x, right_top.y, radius, mPaint);
        canvas.drawCircle(left_bottom.x, left_bottom.y, radius, mPaint);
        //画网格
        mPaint.setStrokeWidth(line_weight_light);
        float startX = left_top.x;
        float startY = left_top.y;
        for (int i = 0; i < 3; i++) {
            startX = startX + line_gap;
            canvas.drawLine(startX, left_top.y, startX, left_bottom.y, mPaint);
        }

        for (int i = 0; i < 3; i++) {
            startY = startY + line_gap;
            canvas.drawLine(left_top.x, startY, right_top.x, startY, mPaint);
        }
//        canvas.drawLine(left_bottom.x,left_bottom.y,right_top.x,right_top.y,mPaint);
        //画虚线
        mPaint.setPathEffect(dashPathEffect);
        canvas.drawLine(left_bottom.x, left_bottom.y, right_top.x, right_top.y, mPaint);
        mPaint.setPathEffect(null);
        mPaint.setStrokeWidth(line_weight_bold);

//        mPath.reset();
        mPath.moveTo(left_bottom.x, left_bottom.y);
//        mPath.quadTo(controlPoint.x, controlPoint.y, right_top.x, right_top.y);
        canvas.drawPath(mPath, beislPaint);
        mPaint.setStyle(Paint.Style.FILL);
        //画触摸点
        canvas.drawCircle(controlPoint.x, controlPoint.y, radius, mPaint);
        //画坐标值text
        if (null != text_coordinate)
            drawText(canvas, controlPoint, radius, mPaint);
    }

    private void drawText(Canvas canvas, PointF controlPoint, int radius, Paint paint) {
        paint.setTextSize(textSize);
        float textWidth = mPaint.measureText(text_coordinate);
        // 文字baseline在y轴方向的位置
        float baseLineY = Math.abs(mPaint.ascent() + mPaint.descent()) / 2;
        float sx ;
        float sy = controlPoint.y + baseLineY;
        if (sy >= (width + line_length - dp_4) / 2f) {
            sy = (width + line_length - dp_4) / 2f;
        }

        if (sy <= (width - line_length) / 2f + baseLineY * 3) {
            sy = (width - line_length) / 2f + baseLineY * 3;
        }

        if (controlPoint.x + controlPoint.y <= line_length) {
            sx = controlPoint.x + radius * 2;
        } else {
            sx = controlPoint.x - radius * 2 - textWidth;
        }
        canvas.drawText(text_coordinate, sx, sy, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                mPath.reset();//reset方法应该放在此处,因为path初始化是在下面的initSuffix方法中,如果在onDraw或initSuffix中调用,则会将已经计算好的path复位,导致绘制无效
                mPath.moveTo(left_bottom.x, left_bottom.y);//应在此处调用,否则会画一条(0,0)过来的线
                controlPoint.x = (int) event.getX();
                controlPoint.y = (int) event.getY();
                //约束x
                if (controlPoint.x > (width + line_length) / 2f)
                    controlPoint.x = (width + line_length) / 2f;
                if (controlPoint.x < (width - line_length) / 2f)
                    controlPoint.x = (width - line_length) / 2f;
                if (controlPoint.y > (width + line_length) / 2f)
                    controlPoint.y = (width + line_length) / 2f;
                if (controlPoint.y < (width - line_length) / 2f)
                    controlPoint.y = (width + line_length) / 2f;
                //计算y
                initSuffix();
                if (mOnCurveChangeListener != null) {
                    text_coordinate = mOnCurveChangeListener.getFixedCoordinate(controlPoint,left_bottom,right_top);
                    mOnCurveChangeListener.onCurveDragged(text_coordinate);
                }
                invalidate();
                break;
        }
        return true;
    }

    //求方程系数,假设函数解析式 y = a*x*x + b * x + c,此处使用二次函数曲线,没有使用二阶贝塞尔曲线,因为贝塞尔曲线控制点不在曲线上,导致曲线上的坐标获取困难,没想到好的方案
    private void initSuffix() {
        double temp1 = (left_bottom.y - right_top.y) * (left_bottom.x - controlPoint.x) -
                (left_bottom.y - controlPoint.y) * (left_bottom.x - right_top.x);

        double temp2 = (left_bottom.x * left_bottom.x - right_top.x * right_top.x) * (left_bottom.x - controlPoint.x) -
                (left_bottom.x * left_bottom.x - controlPoint.x * controlPoint.x) * (left_bottom.x - right_top.x);
        if (temp2 != 0) {
            //系数a
            double a = temp1 / temp2;
            double tmp3 = left_bottom.y - right_top.y - a * (left_bottom.x * left_bottom.x - right_top.x * right_top.x);
            double tmp4 = left_bottom.x - right_top.x;

            if (tmp4 != 0) {
                //系数b
                double b = tmp3 / tmp4;
                //系数c
                double c = left_bottom.y - left_bottom.x * left_bottom.x * a - left_bottom.x * b;
                for (float i = left_bottom.x; i <= right_top.x; i += 3) {
                    double y = a * i * i + b * i + c;
                    //约束y的值,其中加或减去dp_4是一个经验值,避免与边框重合
                    if (y <= (width - line_length + dp_4) / 2f) {
                        y = (width - line_length + dp_4) / 2f;
                    }
                    if (y >= (width + line_length - dp_4) / 2f) {
                        y = (width + line_length - dp_4) / 2f;
                    }

                    mPath.lineTo(i, (float) y);//key
                }
            }
        }
    }

    private OnCurveChangeListener mOnCurveChangeListener;

    public void setOnCurveChangeListener(OnCurveChangeListener onCurveChangeListener) {
        mOnCurveChangeListener = onCurveChangeListener;
    }

    public interface OnCurveChangeListener {
        //触摸点改变
        void onCurveDragged(String coordinate);
        //将触摸点坐标转换成对应的值(根据需要)
        String getFixedCoordinate(PointF contrlPoint,PointF leftBottom,PointF rightTop);
    }
}

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

推荐阅读更多精彩内容