美文网首页安卓android项目知识点
Android自定义TextView简单背景图,省去在drawa

Android自定义TextView简单背景图,省去在drawa

作者: zhangdong0921 | 来源:发表于2019-10-19 11:32 被阅读0次
  • 思考:
    UI效果图总是喜欢给出各种背景,来突出效果
    eg:


    线条样式(线条角度,颜色,宽度)
填充样式(角度,背景色)

常规的实现方法,我们会采取在Drawable文件夹下新建shape资源,来绘制各种背景样式,然后设置给我们需要用到的view控件,这样就会涉及到,角度大小不一样、线条宽度不一样、颜色值不一样;那么再新建shape.xml文件吧....

下面来看一下代码方式实现

package com.test.zd.baselibrary.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import com.test.zd.baselibrary.R;


/**
 * Package: com.example.zd.baseapi.view
 * <p>
 * describe: 有简单背景图案的textView
 * 简单的背景图可以用这个,省去自定义各种shape资源
 *
 * @author zhangdong on 2019/10/18 0018.
 * @version 1.0
 * @see .
 * @since 1.0
 */
public class ShapeBgTextView extends AppCompatTextView {

    //注意统一尺寸单位 获取到的都是px值  所以设置的都转成px使用

    private Paint mPaint;
    private RectF rectF;
    private int drawShapeColor;     //周围一圈线颜色
    private int lineWidth;          //周围线宽度 单位转换成px
    private int corner;             //圆角大小 单位转换成px
    private int shapeStyle;         //图形样式 0-画线  !=0 填充整个view
    private boolean haveBg;         //是否画背景

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

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

    public ShapeBgTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShapeBgTextView);
        //是否有背景线
        haveBg = typedArray.getBoolean(R.styleable.ShapeBgTextView_showBgShape, false);
        //线颜色
        drawShapeColor = typedArray.getColor(R.styleable.ShapeBgTextView_shapeColor, Color.GRAY);
        //线宽度 dp 转换成px
        lineWidth = typedArray.getInteger(R.styleable.ShapeBgTextView_bgLineWidth, 1);
        lineWidth = dp2Px(lineWidth);
        //圆角大小 dp 转换成px
        corner = typedArray.getInteger(R.styleable.ShapeBgTextView_cornerSize, 0);
        corner = dp2Px(corner);
        //画的样式
        shapeStyle = typedArray.getInt(R.styleable.ShapeBgTextView_shapeStyle, 0);

        typedArray.recycle();

        //初始化画笔
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        if (shapeStyle == 0) {
            //样式空心画线
            mPaint.setStyle(Paint.Style.STROKE);
        } else {
            //填充模式画形状
            mPaint.setStyle(Paint.Style.FILL);
        }
        //抗锯齿
        mPaint.setAntiAlias(true);
        //线条首位样式 平头这样转弯比较圆滑
        mPaint.setStrokeCap(Paint.Cap.BUTT);
        //画笔颜色
        mPaint.setColor(drawShapeColor);
        //画笔宽度
        mPaint.setStrokeWidth(lineWidth);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        //view的最短边
        int minW = Math.min(w, h);

        //画线的宽度都大于view的短边的一半了 一来一回画出来的线都占满了view
        //那么强制线宽就是短边的一半减一点 不然临界值画不出来
        //即 0 < lineWidth < (minW)/2
        if (lineWidth >= (minW >> 1)) {
            lineWidth = (minW >> 1);
            //重置画笔宽度
            mPaint.setStrokeWidth(lineWidth);
            //此时要画的矩形短边近似为lineWidth
            if (corner > (lineWidth >> 1)) {
                corner = (lineWidth >> 1);
            }
        } else {
            //画笔宽度没有超限
            //检查圆角是否超过当前允许的最大值
            if (corner > ((minW - lineWidth) >> 1)) {
                corner = ((minW - lineWidth) >> 1);
            }
        }

        if (corner <= 0)
            corner = 0;

        //view相似的矩形 这个就行其实是减去了线绘制宽度的内部矩形
//              _________________
//              |  ___________  |
//              |  |         |  |
//              |  |         |  |
//              |  |_________|  |
//              |_______________|
        //画线的矩形
        if (shapeStyle == 0)
            rectF = new RectF(lineWidth >> 1, lineWidth >> 1,
                    w - (lineWidth >> 1), h - (lineWidth >> 1));
        else
            //填充模式的矩形
            rectF = new RectF(0, 0, w, h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //绘制我们自己要的背景
        drawLineRect(canvas);

        //textView自己的绘制
        super.onDraw(canvas);
    }

    /**
     * 画外圈的线
     *
     * @param canvas .
     */
    private void drawLineRect(Canvas canvas) {
        //画形
        if (haveBg) {
            //清除view原有背景
            setBackgroundResource(0);

            if (corner == 0) {
                //圆角为0dp 则直接画矩形
                canvas.drawRoundRect(rectF, 0, 0, mPaint);
                //补四个角的点  不然画笔线太粗的时候四个角是空白的
                canvas.drawPoint(rectF.left, rectF.bottom, mPaint);
                canvas.drawPoint(rectF.left, rectF.top, mPaint);
                canvas.drawPoint(rectF.right, rectF.top, mPaint);
                canvas.drawPoint(rectF.right, rectF.bottom, mPaint);
            } else {
                //画圆角矩形
                canvas.drawRoundRect(rectF,
                        corner + (lineWidth >> 1),
                        corner + (lineWidth >> 1),
                        mPaint);
            }
        }
    }

    private int dp2Px(float dpValue) {
        float density = getResources().getDisplayMetrics().density;
        return (int) (dpValue * density);
    }
}

需要在values文件夹下新建attr.xml文件,在里面定义需要用到的属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="ShapeBgTextView">
        <!--是否显示我们自己画的背景-->
        <attr name="showBgShape" format="boolean" />
        <!--自己画的背景色-->
        <attr name="shapeColor" format="color|reference" />
        <!--线条模式的线条宽度 dp单位 设置时为int-->
        <attr name="bgLineWidth" format="integer" />
        <!--圆角的大小 dp单位 设置时为int-->
        <attr name="cornerSize" format="integer" />
        <!--画的背景样式-->
        <attr name="shapeStyle" format="enum">
            <!--周围线条样式-->
            <enum name="line" value="0" />
            <!--内部填充样式-->
            <enum name="fill" value="1" />
        </attr>
    </declare-styleable>

</resources>

现在来试试再实现刚才的UI效果会是怎样:

 <com.test.zd.baselibrary.view.ShapeBgTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="30dp"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:paddingRight="10dp"
        android:paddingBottom="5dp"
        android:text="推荐"
        android:textColor="@color/colorAccent"
        android:textSize="16sp"
        app:bgLineWidth="1"
        app:cornerSize="5"
        app:shapeColor="@color/colorAccent"
        app:shapeStyle="line"
        app:showBgShape="true"
        app:layout_constraintRight_toLeftOf="@+id/shape_view"
        app:layout_constraintTop_toTopOf="@+id/shape_view"
        />
    <!--
        app:bgLineWidth="1"     设置线条宽度
        app:cornerSize="5"      设置圆角大小
        app:shapeColor="@color/colorAccent"     设置线条颜色
        app:shapeStyle="line"   设置shape的样式 line / fill
        app:showBgShape="true"  是否要画我们需要的背景 true画我们的/false就是正常的textView
        -->

    <com.test.zd.baselibrary.view.ShapeBgTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:paddingLeft="15dp"
        android:paddingTop="5dp"
        android:paddingRight="15dp"
        android:paddingBottom="5dp"
        android:text="来源"
        android:textColor="@android:color/white"
        app:cornerSize="20"
        app:shapeColor="#40000000"
        app:shapeStyle="fill"
        app:showBgShape="true"
        app:layout_constraintLeft_toRightOf="@+id/shape_view"
        app:layout_constraintTop_toTopOf="@+id/shape_view"
        />

运行效果:


image.png

已经能够通过代码设置我们需要的简单背景样式。

扩展

  • 这个只是针对textview的简单背景样式,复杂的样式还是只能通过切图或者shape.xml方式;
  • 其他的view也能通过这些方式实现,又是一大堆自定义;
  • 画有阴影的背景???
  • 背景色的点击切换效果 --> 实现shape的selected效果

相关文章

网友评论

    本文标题:Android自定义TextView简单背景图,省去在drawa

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