美文网首页
自定义一个具有倒角的三角形标签(RoundLabelTextVi

自定义一个具有倒角的三角形标签(RoundLabelTextVi

作者: NamelessPeople | 来源:发表于2017-12-15 14:14 被阅读0次

http://blog.csdn.net/namelessperson/article/details/78739778

小子第一次写博客,格式不太会,大家见谅。
在Google翻译的帮助下,用了自己的所有的英文知识取了一个控件名字RoundLabelTextView。

先看效果图

image

完整代码 https://github.com/NamelessPeople/RoundLabelTextView

实现过程

画图形

创建一个RoundLabelTextView extend View类实现其构造方法;
分析:一个有倒角的三角形分成两部分:缺角的三角形(梯形)和1/4的 圆;

先画1/4的圆

    int radius=100;
    int labelLength= 400;
    
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawShape(canvas);
    }
    
    private void drawShape(Canvas canvas) {
        float[] radii = new float[]{this.radius, this.radius, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        Path path = new Path();
        RectF roundRect = new RectF();
        roundRect.set(0.0F, 0.0F, this.radius, this.radius);
        path.addRoundRect(roundRect, radii, Path.Direction.CW);
        path.close();
        canvas.drawPath(path, paint);
    }
    private void drawShape(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        Path path = new Path();
        path.moveTo(this.radius, 0);
        path.lineTo(this.labelLength, 0);
        path.lineTo(0, this.labelLength);
        path.lineTo(0, radius);
        path.close();
        canvas.drawPath(path, paint);
    }

如图:

left right

将两段合并在一起就成了有倒角的三角形;

在合成需要注意的就是path画梯形和画1/4圆的顺序(保持同方向):

path画梯形的先后顺序:如果1-2-3-4顺时针,那么画圆的顺序也是顺时针 Path.Direction.CW;

path画梯形的先后顺序:如果4-3-2-1逆时针,那么画圆的顺序也是逆时针 Path.Direction.CCW;

这里写图片描述

如果顺序相对就会出现一个问题:


这里写图片描述

具体为什么我也不太清楚,求指出;

设置文字

最主要的就是旋转文字和移动位置

这里写图片描述

将图像绘制好了之后,根据中学老师教的几何知识:
将画布以中心(labelLength /2,labelLength /2)旋转-45度。
再将画布向Y轴移动labelLength / 2.0 -文字高度(文字大小);

    String text = "RoundLabel";
    int width;
    int height;
    int textSize = 50;
    
    private void drawContentText(Canvas canvas) {
        Rect rectText = new Rect();
        Paint contentPaint = new Paint();
        contentPaint.setColor(Color.BLACK);
        contentPaint.setTextSize(textSize);
        contentPaint.getTextBounds(text, 0, text.length(), rectText);
        width = rectText.width();
        height = textSize;
        canvas.rotate(-45.0, labelLength / 2, labelLength / 2);
        canvas.translate(0.0, labelLength / 2 -height);
        canvas.drawText(text, 0, height, contentPaint);
    }

[图片上传失败...(image-e017da-1513318485827)]

这样一个标签就完成了;
其他的方向的标签,可以在画图形之前将画布90度的旋转;
其他的细节就看源码吧:https://github.com/NamelessPeople/RoundLabelTextView
谢谢;

相关文章

网友评论

      本文标题:自定义一个具有倒角的三角形标签(RoundLabelTextVi

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