Android 自定义圆形背景替换Shape

先看下效果图,项目中需要动态的设置背景色,而且要求背景为圆形,使用shape不灵活:


1.奉上具体实现代码

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 *
 * Created by yulu on 2018/3/21.
 */


public class RoundBackChange extends View{
    private int color =0xddffffff;
    private Paint mPaint = new Paint();
    public RoundBackChange(Context context) {
        super(context,null);
    }

    public RoundBackChange(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //设置画笔宽度为10px
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RoundBackChange);
        color = array.getColor(R.styleable.RoundBackChange_self_color,color);
        array.recycle();
        mPaint.setColor(color);       //设置画笔颜色
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);  //设置画笔模式为填充
        mPaint.setStrokeWidth(10f);
        mPaint.setAntiAlias(true);


    }

    public void setBackColor(int color){
        this.color = color;
        mPaint.setColor(color);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawCircle(getRight()-getLeft()-getMeasuredWidth()/2, getTop()+getMeasuredHeight()/2,getMeasuredWidth()/3,mPaint);
    }
}

2.在values文件夹下添加attrs文件,自定义颜色属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RoundBackChange">
        <attr name="self_color" format="color"/>
    </declare-styleable>

</resources>

3.在xml中使用

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        >

        <com.anshi.university.RoundBackChange
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:scaleType="centerInside"
            app:self_color="@color/maybe_color_main" />

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:scaleType="centerInside"
            android:layout_gravity="center"
            android:src="@mipmap/ic_launcher"
            />

    </FrameLayout>

end......

猜你喜欢

转载自blog.csdn.net/hardWork_yulu/article/details/79641811