使用透明创建半圆背景可绘制

Create half circle background drawable with transparent

我尝试创建这样的可绘制对象

我写了代码并且几乎可以正常工作

public class GetsugaDrawable extends Drawable {

private final Context context;
private final float radiusScale = 1.2f;
private final float yOffset = 0.3f;

private final int colorLower = Color.RED;
private final int colorUpper = Color.BLACK;

private final Paint upperPaint = new Paint();

public GetsugaDrawable(Context c) {
    context = c;
    upperPaint.setColor(colorUpper);
    upperPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
}

@Override
public void draw(@NonNull Canvas canvas) {
    final Rect bounds = new Rect(getBounds());
    canvas.drawColor(colorLower, PorterDuff.Mode.SRC);
    final float radius = radiusScale * bounds.height();
    final int x = bounds.centerX();
    final float y = (bounds.centerY() - bounds.height() * yOffset) - radius;
    canvas.drawCircle(x, y, radius, upperPaint);
}

@Override
public void setAlpha(int alpha) {
    // ignored TODO impl.
}

@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
    // ignored TODO impl.
}

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

这是我的结果

我试着改变

    private final int colorUpper = Color.BLACK;

    private final int colorUpper = Color.TRANSPARENT;

但是当我运行我的应用程序再次使用透明颜色时,结果是这样的

我做错了什么? 谢谢

添加 upperPaint.setXfermode(新 PorterDuffXfermode(PorterDuff.Mode.CLEAR));

public class GetsugaDrawable extends Drawable {
private final Context context;
private final float radiusScale = 1.2f;
private final float yOffset = 0.3f;

private final int colorLower = Color.RED;
private final int colorUpper = Color.BLACK;

private final Paint upperPaint = new Paint();

public GetsugaDrawable(Context c) {
    context = c;
    upperPaint.setAntiAlias(true);
    upperPaint.setColor(colorUpper);
    upperPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));      
}

@Override
public void draw(@NonNull Canvas canvas) {
    final Rect bounds = new Rect(getBounds());
    canvas.drawColor(colorLower);
    final float radius = radiusScale * bounds.height();
    final int x = bounds.centerX();
    final float y = (bounds.centerY() - bounds.height() * yOffset) - radius;
    canvas.drawCircle(x, y, radius, upperPaint);
}

@Override
public void setAlpha(int alpha) {

}

@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {

}

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

并且不要忘记 view.setLayerType(View.LAYER_TYPE_HARDWARE, null);在目标视图中

您可以更改 draw 功能。

@Override
public void draw(@NonNull Canvas canvas) {
    final Rect bounds = new Rect(getBounds());
    final float radius = radiusScale * bounds.height();
    final int x = bounds.centerX();
    final float y = (bounds.centerY() - bounds.height() * yOffset) - radius;
    Path path = new Path();
    path.addCircle(x, y, radius, CW);
    canvas.clipPath(path, Region.Op.DIFFERENCE);
    canvas.drawColor(colorLower);
}

试试这个。