自定义View_使用canvas画一个斜角标(二)

之前写过一个倾斜角标的实现效果,那么这次带来另一种形式的角标实现,虽然与上次的展示形式差别不大,但是实现方式大大不同,先来看下效果图。

角标

实现原理


1.使用Path连接成一个三角形的形状,绘制Path;
2.绘制文字;

没了,就这些,很简单吧~

实现过程

这里以角标显示在右上角为例讲解一下实现的过程,从效果图来看,我们还需要考虑一个细节问题,那就是圆角,因为为了一定的扩展性我们必须把这个细节考虑在内,那么圆角的实现也很简单,在顶端添加一小段圆弧即可。

示意图

绘制背景

从示意图中看出,从1到2的位置lineTo,从2到3的位置addArc,从3到4以及再回到原点的位置lineTo,最后形成一个封闭空间,即可绘制完成。

path.moveTo(0, 0);
path.lineTo(getWidth() - mRadius, 0);
path.addArc(new RectF(getWidth() - mRadius, 0, getWidth(), mRadius), -90, 90);
path.lineTo(getWidth(), getHeight());
path.lineTo(0, 0);
path.close();
//绘制
canvas.drawPath(path, mPaint);

那么这里的圆弧我们需要设置一个变量mRadius来控制这个圆角的大小,再根据此值计算图中各个位置点的坐标值,然后操作Path,最后绘制即可。

绘制文字

OK,到了最后一步了,与以往的文字绘制不同,这次的文字有一个切斜的效果,所以我们考虑使用drawTextOnPath这个方法,该方法可以沿着Path路径绘制文本,来看一下参数都代表什么意思。

/**
 * Draw the text, with origin at (x,y), using the specified paint, along the specified path. The
 * paint's Align setting determins where along the path to start the text.
 *
 * @param text The text to be drawn
 * @param path The path the text should follow for its baseline
 * @param hOffset The distance along the path to add to the text's starting position
 * @param vOffset The distance above(-) or below(+) the path to position the text
 * @param paint The paint used for the text (e.g. color, size, style)
 */
public void drawTextOnPath(@NonNull String text, @NonNull Path path, float hOffset,
        float vOffset, @NonNull Paint paint) {
    super.drawTextOnPath(text, path, hOffset, vOffset, paint);
}

其中text指绘制的文本内容,path指路径,hOffset参数指定水平偏移、vOffset指定垂直偏移,paint即画笔。

根据我们想要的文字水平居中效果即可确定hOffset以及vOffset的值,代码如下:

if (!TextUtils.isEmpty(mText)) {
    mPathText.moveTo(0, 0);
    mPathText.lineTo(getWidth(), getHeight());
    //测量文字的宽度
    float textWidth = mPaintText.measureText(mText);
    //求出对角线长度
    float diagonalWidth = (float) Math.sqrt(getWidth() * getWidth() + getHeight() * getHeight());
    //文字水平居中
    float hOffset = (diagonalWidth - textWidth) / 2;
    canvas.drawTextOnPath(mText, mPathText, hOffset, -mTextMarginBottom, mPaintText);
}

其中mTextMarginBottom的值是我自定义的一个可控变量,这里用来作为vOffset的实参传递进去。
为了提高控件的扩展性灵活性,我们还可以自定义一些属性去更灵活的控制,比如颜色尺寸等,代码如下:

<declare-styleable name="MarkerView">
    <!--角标文字-->
    <attr name="mv_text" format="string" />
    <!--角标文字尺寸-->
    <attr name="mv_textSize" format="dimension" />
    <!--角标文字颜色-->
    <attr name="mv_textColor" format="color" />
    <!--角标背景颜色-->
    <attr name="mv_backgroundColor" format="color" />
    <!--角标背景圆角-->
    <attr name="mv_backgroundRadius" format="dimension" />
    <!--角标文字距离底部的距离-->
    <attr name="mv_textMarginBottom" format="dimension" />
    <!--角标所处位置-->
    <attr name="mv_gravityPosition" format="enum">
        <enum name="leftTop" value="1" />
        <enum name="rightTop" value="2" />
    </attr>
</declare-styleable>

然后在构造函数中使用TypedArray获取这些属性值就可以了,具体请看完整代码。

完整代码

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.zhuyong.progressbar.R;

public class MarkerView extends View {

    /**
     * 绘制角标的画笔
     */
    private Paint mPaint;
    /**
     * 绘制角标文字的画笔
     */
    private Paint mPaintText;
    /**
     * 文字距离底部的距离
     */
    private float mTextMarginBottom = 5;
    /**
     * 圆角
     */
    private float mRadius = 0;
    /**
     * 左上角还是右下角
     */
    private int location;
    /**
     * 绘制在左上角
     */
    public static final int LEFT_TOP = 1;
    /**
     * 绘制在右上角
     */
    public static final int RIGHT_TOP = 2;
    /**
     * 背景Path
     */
    private Path path = new Path();
    /**
     * 角标文字的路径Path
     */
    private Path mPathText = new Path();
    /**
     * 背景色 默认红色
     */
    private int mBackgroundColor = Color.RED;
    /**
     * 文字颜色
     */
    private int mTextColor = Color.WHITE;
    /**
     * 文字尺寸
     */
    private float mTextSize = 12;
    /**
     * 文字
     */
    private String mText = "";

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

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

    public MarkerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //使用TypedArray获取自定义属性值
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MarkerView);
        location = array.getInt(R.styleable.MarkerView_mv_gravityPosition, 2);
        mRadius = array.getDimension(R.styleable.MarkerView_mv_backgroundRadius, mRadius);
        mBackgroundColor = array.getColor(R.styleable.MarkerView_mv_backgroundColor, mBackgroundColor);
        mTextMarginBottom = array.getDimension(R.styleable.MarkerView_mv_textMarginBottom, dip2px(context, mTextMarginBottom));
        mText = array.getString(R.styleable.MarkerView_mv_text);
        mTextColor = array.getColor(R.styleable.MarkerView_mv_textColor, mTextColor);
        mTextSize = array.getDimension(R.styleable.MarkerView_mv_textSize, sp2px(context, mTextSize));
        array.recycle();

        init();
    }

    /**
     * 初始化Paint
     */
    private void init() {

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(mBackgroundColor);
        mPaint.setStyle(Paint.Style.FILL);

        mPaintText = new Paint();
        mPaintText.setAntiAlias(true);
        mPaintText.setColor(mTextColor);
        mPaintText.setStyle(Paint.Style.FILL);
        mPaintText.setTextSize(mTextSize);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (location == LEFT_TOP) {
            drawLeftTop(canvas);
        } else {
            drawRightTop(canvas);
        }
    }


    /**
     * 绘制在左上角
     *
     * @param canvas
     */
    private void drawLeftTop(Canvas canvas) {

        path.moveTo(0, getHeight());
        path.lineTo(0, mRadius);

        path.addArc(new RectF(0, 0, mRadius, mRadius), -180, 90);

        path.lineTo(getWidth(), 0);
        path.lineTo(0, getHeight());
        path.close();

        canvas.drawPath(path, mPaint);

        if (!TextUtils.isEmpty(mText)) {

            mPathText.moveTo(0, getHeight());
            mPathText.lineTo(getWidth(), 0);
            //测量文字的宽度
            float textWidth = mPaintText.measureText(mText);
            //求出对角线长度
            float diagonalWidth = (float) Math.sqrt(getWidth() * getWidth() + getHeight() * getHeight());
            //文字水平居中
            float hOffset = (diagonalWidth - textWidth) / 2;

            canvas.drawTextOnPath(mText, mPathText, hOffset, -mTextMarginBottom, mPaintText);
        }
    }

    /**
     * 绘制在右上角
     *
     * @param canvas
     */
    private void drawRightTop(Canvas canvas) {

        path.moveTo(0, 0);
        path.lineTo(getWidth() - mRadius, 0);

        path.addArc(new RectF(getWidth() - mRadius, 0, getWidth(), mRadius), -90, 90);

        path.lineTo(getWidth(), getHeight());
        path.lineTo(0, 0);
        path.close();

        canvas.drawPath(path, mPaint);


        if (!TextUtils.isEmpty(mText)) {

            mPathText.moveTo(0, 0);
            mPathText.lineTo(getWidth(), getHeight());
            //测量文字的宽度
            float textWidth = mPaintText.measureText(mText);
            //求出对角线长度
            float diagonalWidth = (float) Math.sqrt(getWidth() * getWidth() + getHeight() * getHeight());
            //文字水平居中
            float hOffset = (diagonalWidth - textWidth) / 2;

            canvas.drawTextOnPath(mText, mPathText, hOffset, -mTextMarginBottom, mPaintText);
        }
    }

    public float getmTextMarginBottom() {
        return mTextMarginBottom;
    }

    public void setmTextMarginBottom(float mTextMarginBottom) {
        this.mTextMarginBottom = mTextMarginBottom;
    }

    public float getmRadius() {
        return mRadius;
    }

    public void setmRadius(float mRadius) {
        this.mRadius = mRadius;
    }

    public int getLocation() {
        return location;
    }

    public void setLocation(int location) {
        this.location = location;
    }

    public int getmBackgroundColor() {
        return mBackgroundColor;
    }

    public void setmBackgroundColor(int mBackgroundColor) {
        this.mBackgroundColor = mBackgroundColor;
    }

    public int getmTextColor() {
        return mTextColor;
    }

    public void setmTextColor(int mTextColor) {
        this.mTextColor = mTextColor;
    }

    public float getmTextSize() {
        return mTextSize;
    }

    public void setmTextSize(float mTextSize) {
        this.mTextSize = mTextSize;
    }

    public String getmText() {
        return mText;
    }

    public void setmText(String mText) {
        this.mText = mText;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

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

推荐阅读更多精彩内容

  • 【Android 自定义View之绘图】 基础图形的绘制 一、Paint与Canvas 绘图需要两个工具,笔和纸。...
    Rtia阅读 11,623评论 5 35
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,960评论 3 119
  • 时间又过去了几天,最近一直在买买买,买了很多的衣服,浪费了很多时间,所以在简书书写的时间就少了很多,我也是个爱...
    暖心空间站阅读 261评论 0 3
  • 一条路漫长 一个身影晃 黄叶跌满地 心情换不了季 灵魂留在原地 挥袖而已 恶意失忆 寡欢的面具 有何干系
    再看长安花阅读 165评论 0 0
  • 早上起的很早。 骑新装备去公司。 大概有工作是个好事。因为你有事干,所以没空瞎想。只不过只要稍稍一懈怠的时候,思念...
    长命与你阅读 155评论 0 0