任务如下:在它上面有一个背景图像,有必要在其中心施加一个半透明的背景是完全透明的圆圈。在这种情况下,背景图像 - 显示具有当前坐标的地图。即卡应该过他们的生活。卡片的顶部以半透明薄膜的形式在中心切出一个圆圈。 请准备以下代码:
public class CircleView extends View {
private Paint srcPaint;
private Paint dstPaint;
public CircleView(Context context) {
this(context, null, 0);
}
public CircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
float centerX = width / 2;
float centerY = height / 2;
float circleRadius = Math.min(width, height) / 5;
canvas.drawRect(0, 0, width, height, dstPaint);
canvas.drawCircle(centerX, centerY, circleRadius, srcPaint);
}
private void init() {
srcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
srcPaint.setColor(Color.WHITE);
srcPaint.setStyle(Paint.Style.FILL);
srcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
dstPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
dstPaint.setColor(Color.argb(221, 255, 217, 32));
dstPaint.setStyle(Paint.Style.FILL);
}
}
但不是透明区域变成不透明的黑色圆圈。做错了什么或缺少什么?
答案 0 :(得分:0)
我在这里找到了解决方案:Punch a hole in a rectangle overlay with HW acceleration enabled on View。有必要绘制位图,然后将其放在画布上。因此,我们得到以下代码:
public class CircleView extends View {
private static final String TAG = "CircleView";
private Paint srcPaint;
public CircleView(Context context) {
this(context, null, 0);
}
public CircleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
float centerX = width / 2;
float centerY = height / 2;
float circleRadius = Math.min(width, height) / 5;
Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas layer = new Canvas(background);
layer.drawColor(getResources().getColor(R.color.transparent_yellow));
layer.drawCircle(centerX, centerY, circleRadius, srcPaint);
canvas.drawBitmap(background, 0, 0, null);
}
private void init() {
srcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
srcPaint.setColor(Color.WHITE);
srcPaint.setStyle(Paint.Style.FILL);
srcPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
}
}