自定义圆角TextView 背景色

本文介绍了一种使用自定义视图实现圆角按钮的方法。通过创建一个继承自TextView的CirButton类,并在构造函数中设置画笔样式、颜色及圆角大小等属性,最终在onDraw方法中绘制出圆角矩形背景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发工程中可能会写很多不同颜色 倒角的shape 作为TextView 或Button的北京实现倒角的效果


管理先来张图



代码如下:

package com.yighao.secondcar.secondHandCar.customView;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.TextView;

import com.yighao.secondcar.R;
import com.yighao.secondcar.secondHandCar.utils.DensityUtils;

/**
 * Created by Administrator on 2017/2/16 0016.
 */

public class CirButton extends TextView {

    private Paint mPaint;

    private int radiu;

    public CirButton(Context context) {
        super(context);
    }

    public CirButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(5);
        mPaint.setStyle(Paint.Style.FILL);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.cir_button);

        int resourceId = typedArray.getResourceId(R.styleable.cir_button_cirColor, R.color.blue);

        int color = context.getResources().getColor(resourceId);

        mPaint.setColor(color);
        int integer = typedArray.getInteger(R.styleable.cir_button_cirRadiu, 10);
        radiu = DensityUtils.dp2px(context, integer);
        typedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        RectF rectF = new RectF(0, 0, getMeasuredWidth(), getMeasuredHeight());
        canvas.drawRoundRect(rectF, radiu, radiu, mPaint);
        super.onDraw(canvas);
    }
}
只是在OnDraw方法中画了一个圆角矩形  切记在super之前画


自定义两个属性 :


<resources>

    <declare-styleable name="cir_button">
        <attr name="cirColor" format="reference" />
        <attr name="cirRadiu" format="reference|integer" />
    </declare-styleable>
</resources>

用法如下:


<com.yighao.secondcar.secondHandCar.customView.CirButton
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="30dp"
    android:gravity="center"
    android:text="adgdgg"
    app:cirColor="@color/orange"  背景颜色
    app:cirRadiu="10" />            倒角大小  单位为dp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值