HalfCircleDrawable.java 2.6 KB
Newer Older
konghaorui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
package com.yidianling.uikit.custom.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.VectorDrawable;

/**
 * @author harvie
 * 自定义半圆斜角drawable
 */
@SuppressLint("NewApi")
public class HalfCircleDrawable extends VectorDrawable {

    private Context context;

    private int width;
    private int height;

    //左上角节点x坐标
    private int leftTopX;
    //圆弧x轴半径
    private int circleRadiusX;
    //右上x坐标
    private int rightTopX;
    //右下角x轴坐标
    private int rightBottomX;

    private int defaultColor;

    private boolean reverse; //是否反转

    /**
     *
     * @param context
     * @param reverse 是否反转,默认圆弧居右侧
     * @param mColor 画笔颜色
     */
    public HalfCircleDrawable(Context context, boolean reverse, int mColor) {
        this.context = context;
        this.defaultColor = mColor;
        this.reverse = reverse;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        width = bounds.right;
        height = bounds.bottom;

        leftTopX = dp2px(8f);
        circleRadiusX = height/2;
        rightTopX = width-circleRadiusX;
        rightBottomX = leftTopX;
    }

    @Override
    public void draw( Canvas canvas) {

        if (reverse){
            canvas.rotate(180,width/2,height/2);
        }

        Paint paint = new Paint();
        paint.setColor(defaultColor);
        paint.setAntiAlias(true);

        Path path = new Path();
        path.moveTo(leftTopX,0);
        path.lineTo(rightTopX,0);
        RectF rectF = new RectF();
        rectF.left = rightTopX-circleRadiusX;
        rectF.top = 0;
        rectF.right = rightTopX+circleRadiusX;
        rectF.bottom = height;
        path.arcTo(rectF,270,180);
        path.lineTo(0,height);
        path.lineTo(leftTopX,0);
        path.close();

        canvas.drawPath(path,paint);

        if (reverse){
            canvas.rotate(180,width/2,height/2);
        }
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @SuppressLint("WrongConstant")
    @Override
    public int getOpacity() {
        return 5;
    }

    private int dp2px(float dp){
        float density = context.getResources().getDisplayMetrics().density;
        return (int)(dp*density);
    }

}