Android 中框外的颜色,同时保持框透明?
Colour outside a box in Android, while keeping the box transparent?
我的 Android 应用程序中有一个框,它需要是透明的,同时用特定颜色填充框外框架的其余部分。
如何在 Canvas 或 OpenCV 或任何其他方式中做到这一点?
这是一个带有透明孔的圆的示例,您可以使用矩形而不是圆来实现相同的效果。
public class OverlayWithHoleImageView extends ImageView {
private RectF circleRect;
private int radius;
public OverlayWithHoleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
//In versions > 3.0 need to define layer Type
if (android.os.Build.VERSION.SDK_INT >= 11)
{
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public void setCircle(RectF rect, int radius) {
this.circleRect = rect;
this.radius = radius;
//Redraw after defining circle
postInvalidate();
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(circleRect != null) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(getResources().getColor(android.R.color.black));
paint.setStyle(Paint.Style.FILL);
canvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(circleRect, radius, radius, paint);
}
}
}
参考:Medium
我的 Android 应用程序中有一个框,它需要是透明的,同时用特定颜色填充框外框架的其余部分。
如何在 Canvas 或 OpenCV 或任何其他方式中做到这一点?
这是一个带有透明孔的圆的示例,您可以使用矩形而不是圆来实现相同的效果。
public class OverlayWithHoleImageView extends ImageView {
private RectF circleRect;
private int radius;
public OverlayWithHoleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
//In versions > 3.0 need to define layer Type
if (android.os.Build.VERSION.SDK_INT >= 11)
{
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public void setCircle(RectF rect, int radius) {
this.circleRect = rect;
this.radius = radius;
//Redraw after defining circle
postInvalidate();
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(circleRect != null) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(getResources().getColor(android.R.color.black));
paint.setStyle(Paint.Style.FILL);
canvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRoundRect(circleRect, radius, radius, paint);
}
}
}
参考:Medium