TextView帶背景

需求

日常有些需求,就是有圓角的控件,不太想弄太多的drawable,就自定義一個(gè)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:根據(jù)給定的顏色,生成默認(rèn)圓角背景圖
 */
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的材料庫里已經(jīng)提供了這種功能的控件了,等更新了去看看。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容