繁体   English   中英

Android椭圆形2种颜色

[英]Android oval shape 2 colors

我有一个线性布局视图,其背景我已设置为椭圆形纯色。 到目前为止,我的背景是圆圈。 现在我想实现相同的,即使用形状drawable得到一个2种颜色的圆。 请参照附件。

在此输入图像描述

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <gradient
        android:centerX="-1"
        android:type="sweep"
        android:startColor="color1"
        android:endColor="color2"
        />

</shape>

在drawable文件夹shape.xml中创建shape.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<gradient android:startColor="#0000FF" android:endColor="#00FF00"
android:angle="270"/>
</shape>

这可能会迟到,但我很难找到好的答案,所以听听我的看法。

我使用自定义drawable绘制圆,并使用一个LinearGradient着色器,由position数组配置,没有渐变过渡。 渐变线方向在LinearGradient构造函数中配置(此处为对角线)。

public class MultiColorCircleDrawable extends Drawable {

    private Paint paint;
    private int[] colors;

    public MultiColorOvalDrawable(int[] colors) {
        this.colors = colors;
    }

    private void init() {
        paint = new Paint();
        paint.setShader(createShader());
    }

    private Shader createShader() {
        int[] colorsArray = new int[colors.length * 2];
        float[] positions = new float[colors.length * 2];

        for (int i = 0; i < colors.length; i++) {
            int y = i * 2;
            int color = colors[i];
            colorsArray[y] = color;
            colorsArray[y+1] = color;
            positions[y] = 1f / colors.length * i;
            positions[y+1] = 1f / colors.length * (i+1);
        }

        Rect bounds = getBounds();
        int width = bounds.right - bounds.left;
        int height = bounds.bottom - bounds.top;

        return new LinearGradient(0, 0, width, height, colorsArray, positions, Shader.TileMode.REPEAT);
    }

    @Override
    public void draw(Canvas canvas) {
        if (null == paint) {
            init();
        }

        Rect bounds = getBounds();
        int width = bounds.right - bounds.left;
        int height = bounds.bottom - bounds.top;
        canvas.drawCircle(width/2, height/2, (width/2) - strokeWidth, maskPaint);
    }

    @Override
    public void setAlpha(int i) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.OPAQUE;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM