我有以下代码用于渲染带有圆角的 imageView。
public class RoundedCornerImageView extends ImageView {
private int rounded;
public RoundedCornerImageView(Context context) {
super(context);
}
public RoundedCornerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedCornerImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public int getRounded() {
return rounded;
}
public void setRounded(int rounded) {
this.rounded = rounded;
}
@Override
public void onDraw(Canvas canvas)
{
Drawable drawable = getDrawable();
int w = drawable.getIntrinsicHeight(),
h = drawable.getIntrinsicWidth();
Bitmap rounder = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
Canvas tmpCanvas = new Canvas(rounder);
// We're going to apply this paint eventually using a porter-duff xfer mode.
// This will allow us to only overwrite certain pixels. RED is arbitrary. This
// could be any color that was fully opaque (alpha = 255)
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
xferPaint.setColor(Color.WHITE);
// We're just reusing xferPaint to paint a normal looking rounded box, the 20.f
// is the amount we're rounding by.
tmpCanvas.drawRoundRect(new RectF(0,0,w,h), 10.0f, 10.0f, xferPaint);
// Now we apply the 'magic sauce' to the paint
xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
drawable.draw(canvas);
canvas.drawBitmap(rounder, 0, 0, xferPaint);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background='#a3deef'
>
<com.example.scheduling_android.view.RoundedCornerImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/eventImageView"
android:adjustViewBounds="false"/>
</LinearLayout>
它的工作原理是它确实裁剪了图像的角落。但是,当我尝试在具有背景颜色#a3deef 的线性布局中渲染它时,问题就出现了。生成的显示是#a3deef 的背景颜色,每个图像都显示为圆角,其中 4 个裁剪角全部为黑色。
我应该怎么做才能使裁剪的角落透明而不是黑色?另外,如果有人能向我解释为什么它会变黑,而不是任何其他颜色,那就太好了!
提前致谢。