自定义给TextView加边框

  • 对于实现该功能首先必须要对自定义控件有一定的知识了解
  • 本实例只需要知道
    1、onDraw(Canvas canvas)
    2、onMeasure(int widthMeasureSpec, int heightMeasureSpec)

其实这两个放的作用很明确的,使用Measure重新测量view的空间,使用onDraw绘制需要的样子。
这里主要实现绘制边框, 使用canvas.drawRoundRect(rect,5,5,paint);这个方法就可以很简单的实现。

完整代码:


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

import com.jbh.goldrush.Utils.LogUtils;

@SuppressLint("AppCompatCustomView")
public class BorderTextView extends TextView {

    //绘制边框的的宽度
    private int stroke_width  =  1  ;
    //默认边框的颜色黑色
    private int stroke_color = Color.BLACK ;


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

    public BorderTextView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BorderTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        this.setPadding(5,2,5,2);
        this.setTextSize(8);
        //绘制文字的颜色
        this.setTextColor(stroke_color);
        this.setGravity(Gravity.CENTER);
    }

    /**
     * @param stroke_color
     */
    public void setStrokeColor(int stroke_color) {
        this.stroke_color = stroke_color;
        invalidate();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int w= this.getMeasuredWidth() + stroke_width*2;
        int h = this.getMeasuredHeight() + stroke_width*2;
        LogUtils.LOG_V("w="+w);
        LogUtils.LOG_V("w="+h);
        setMeasuredDimension(w,h);
    }



    @Override
    protected void onDraw(Canvas canvas) {
        this.setTextColor(stroke_color);
        Paint paint=new Paint();
        paint.setStyle(Paint.Style.STROKE);
        //  将边框设为黑色
        paint.setColor(stroke_color);
        paint.setStrokeWidth(2);
        int left = stroke_width ;
        int right = this.getWidth() - stroke_width;
        int top= stroke_width ;
        int bottom = this.getHeight() - stroke_width ;
        RectF rect=new RectF(left,top,right,bottom);
        canvas.drawRoundRect(rect,5,5,paint);
        super.onDraw(canvas);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

将哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值