将圆圈放在图标后面并选择颜色

时间:2018-05-03 12:50:04

标签: android

我必须在我的应用中显示许多图标,每次出现时都会在彩色圆圈内显示;现在我只获得了图标本身,所以我必须自己创建圆圈。我想创建一个自定义视图,但我真的不知道如何实现它!

3 个答案:

答案 0 :(得分:0)

用户向量drawable:https://developer.android.com/reference/android/graphics/drawable/VectorDrawable

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="200dp"
    android:height="200dp"
    android:viewportHeight="64"
    android:viewportWidth="64">

    <path
        android:fillColor="#ff00ff"
        android:pathData="M22,32
        A10,10 0 1,1 42,32
        A10,10 0 1,1 22,32 Z" />
</vector>

答案 1 :(得分:0)

    public class ShapeView extends View {


    int shape;
    int color;
    Paint paint;

    public static final int CIRCLE = 0;
    public static final int SQUARE = 1;

    public ShapeView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.ShapeView,
                0, 0
        );

        try {
            shape = a.getInteger(R.styleable.ShapeView_shape, 0);
            color = a.getColor(R.styleable.ShapeView_color, ContextCompat.getColor(context, R.color.white));
        } finally {
            a.recycle();
        }

        paint = new Paint();
        paint.setColor(color);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        switch (shape) {
            case CIRCLE:
                drawCircle(canvas);
                break;
            case SQUARE:
                drawSquare(canvas);
                break;

        }
    }

    private void drawCircle(Canvas canvas) {
        int x = getWidth() / 2;
        int y = getHeight() / 2;
        canvas.drawCircle(x, y, x, paint);
    }

    private void drawSquare(Canvas canvas) {
        int x = getWidth() / 2;
        int y = getHeight() / 2;
        int right = 2 * x;
        int bottom = 2 * y;
        canvas.drawRect(0, 0, right, bottom, paint);
    }

    public void changeShape(int shape) {
        this.shape = shape;
        invalidate();
        requestLayout();
    }

    public void changeColor(int color) {
        this.color = color;
        invalidate();
    }
}

在资源文件夹

中创建一个attr.xml文件
<declare-styleable name="ShapeView">
    <attr name="shape" format="enum">
        <enum name="circle" value="0" />
        <enum name="square" value="1" />
    </attr>
    <attr name="color" format="color" />
</declare-styleable>

在xml中使用它如下

<com.app.custom.ShapeView
                android:id="@+id/v_recording_state"
                android:layout_width="@dimen/_15sdp"
                android:layout_height="@dimen/_15sdp"
                android:layout_gravity="center"
                app:color="@color/white"
                app:shape="circle" />

答案 2 :(得分:0)

这将有所帮助https://github.com/hdodenhof/CircleImageView

要设置背景颜色,请使用此行 -

google