Android画布:在图像上绘制透明圆圈 [英] Android canvas: draw transparent circle on image
问题描述
我正在创建一个像素狩猎游戏.所以我的活动显示了一个 ImageView.我想创建一个提示告诉我对象在哪里".为此,我需要模糊整个图像,除了围绕对象所在点的圆圈.我可以显示一个半透明的黑色背景,而不是模糊.在Canvas上画一个半透明的矩形是没有问题的.但我不知道如何从中裁剪一个透明的圆圈.结果应如下所示:
I am creating a pixel-hunting game. So my activity shows an ImageView. And I want to create a hint "show me where is the object". For this I need to blur whole image except a circle around a point where the object is located. Instead of blur I can show a just semitransparent black background. There is there is no problem to draw a semitransparent rectangle on the Canvas. But I don't know how to crop a transparent circle from it. The result should look like like this:
请帮助我在 Android SDK 上实现相同的结果.
Please help me to achieve same result on Android SDK.
推荐答案
所以我终于做到了.
首先我在整个视图上绘制一个半透明的黑色矩形.之后使用 PorterDuff.Mode.CLEAR
我剪了一个透明的圆圈来显示猫的位置.
Firstly I draw a semitransparent black rectangle on whole view.
After that using PorterDuff.Mode.CLEAR
I cut a transparent circle to show cat's position.
我在使用 PorterDuff.Mode.CLEAR
时遇到问题:首先我得到的是一个黑色圆圈而不是透明圆圈.
I had problem with PorterDuff.Mode.CLEAR
: firstly I was getting a black circle instead of a transparent one.
感谢 Romain Guy 的评论:在这里评论 我知道我的窗口是不透明的,我应该在另一个位图上绘制.并且只有在 View
的画布上绘制之后.
Thanks to Romain Guy's comments here: comment here I understood that my window is opaque and I should draw on another bitmap. And only after draw on View
's canvas.
这是我的 onDraw
方法:
private Canvas temp;
private Paint paint;
private Paint p = new Paint();
private Paint transparentPaint;
private void init(){
Bitmap bitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
temp = new Canvas(bitmap);
paint = new Paint();
paint.setColor(0xcc000000);
transparentPaint = new Paint();
transparentPaint.setColor(getResources().getColor(android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
protected void onDraw(Canvas canvas) {
temp.drawRect(0, 0, temp.getWidth(), temp.getHeight(), paint);
temp.drawCircle(catPosition.x + radius / 2, catPosition.y + radius / 2, radius, transparentPaint);
canvas.drawBitmap(bitmap, 0, 0, p);
}
这篇关于Android画布:在图像上绘制透明圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!