美文网首页
TextView带背景

TextView带背景

作者: 有点健忘 | 来源:发表于2017-10-25 13:58 被阅读27次

需求

日常有些需求,就是有圆角的控件,不太想弄太多的drawable,就自定义一个textview。需要啥背景,画出来就完事了。
如下图:

QQ截图20171025121908.png

<declare-styleable name="TextViewWithBg">
<attr name="tv_bg_color" format="color" />
<attr name="tv_bg_stroke_color" format="color" />
<attr name="tv_stroke_width" format="dimension" />
<attr name="tv_corner_radius" format="dimension" />
</declare-styleable>

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.support.v7.widget.AppCompatTextView
import android.util.AttributeSet
import com.xr.ruidementality.R

/**
 * Created by Sage on 2017/9/26.
 * Description:根据给定的颜色,生成默认圆角背景图
 */
class TextViewWithBg : AppCompatTextView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        var a = context.obtainStyledAttributes(attrs, R.styleable.TextViewWithBg)
        colorBg = a.getColor(R.styleable.TextViewWithBg_tv_bg_color, context.resources.getColor(R.color.default_color_theme))
        colorStroke = a.getColor(R.styleable.TextViewWithBg_tv_bg_stroke_color, 0)
        strokeWidth = a.getDimensionPixelSize(R.styleable.TextViewWithBg_tv_stroke_width, 0).toFloat()
        cornerRadius=a.getDimensionPixelSize(R.styleable.TextViewWithBg_tv_corner_radius,-1).toFloat()
        paintBg.strokeWidth=strokeWidth
        a.recycle()
    }

    var colorBg: Int = 0
    var colorStroke: Int = 0
    var strokeWidth = 0f
    var cornerRadius=-1f

    var paintBg=Paint(Paint.ANTI_ALIAS_FLAG)

    override fun onDraw(canvas: Canvas) {

        if(cornerRadius<0){
            cornerRadius=height/2-strokeWidth
        }
        var rectF=RectF(strokeWidth,strokeWidth,width-strokeWidth,height-strokeWidth)
        paintBg.color=colorBg
        paintBg.style=Paint.Style.FILL
        canvas.drawRoundRect(rectF,cornerRadius,cornerRadius,paintBg)
        paintBg.color=colorStroke
        paintBg.style=Paint.Style.STROKE

        canvas.drawRoundRect(RectF(strokeWidth/2,strokeWidth/2,width-strokeWidth/2,height-strokeWidth/2),
                cornerRadius,cornerRadius,paintBg)
        super.onDraw(canvas)
    }

}

下图简单的使用,其他属性还是TextView的,

![Uploading QQ截图20171025135605_008522.png . . .]

好像最新28的材料库里已经提供了这种功能的控件了,等更新了去看看。

相关文章

网友评论

      本文标题:TextView带背景

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