Android canvas:在图像上绘制透明圆圈

我正在创建一个像素狩猎游戏。 所以我的活动显示了一个ImageView。 我想创建一个提示“告诉我对象在哪里”。 为此,我需要模糊整个图像,除了对象所在点周围的圆圈以外。 除了模糊之外,我还可以显示半透明的黑色背景。在画布上绘制半透明矩形没有问题。但是我不知道如何从中切出一个透明的圆圈。结果应如下所示:enter image description here

请帮助我在Android SDK上达到相同的结果。

Robert asked 2020-02-14T01:39:39Z
8个解决方案
47 votes

所以最后我设法做到了。

首先,我在整个视图上绘制一个半透明的黑色矩形。之后,使用onDraw,我切割了一个透明的圆圈以显示猫的位置。

我遇到onDraw的问题:首先,我得到的是黑色圆圈,而不是透明的圆圈。

感谢Romain Guy在这里的评论:在这里的评论我知道我的窗口是不透明的,应该在另一个位图上绘制。 并且只有在onDraw的画布上绘制之后。

这是我的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);
}
Robert answered 2020-02-14T01:45:25Z
38 votes

我通过创建自定义LinearLayout来完成此操作:

检查屏幕截图:

enter image description here

CircleOverlayView.java

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/**
 * Created by hiren on 10/01/16.
 */
public class CircleOverlayView extends LinearLayout {
    private Bitmap bitmap;

    public CircleOverlayView(Context context) {
        super(context);
    }

    public CircleOverlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CircleOverlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CircleOverlayView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        if (bitmap == null) {
            createWindowFrame(); 
        }
        canvas.drawBitmap(bitmap, 0, 0, null);
    }

    protected void createWindowFrame() {
        bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); 
        Canvas osCanvas = new Canvas(bitmap);

        RectF outerRectangle = new RectF(0, 0, getWidth(), getHeight());

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(getResources().getColor(R.color.colorPrimary));
        paint.setAlpha(99);
        osCanvas.drawRect(outerRectangle, paint);

        paint.setColor(Color.TRANSPARENT); 
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)); 
        float centerX = getWidth() / 2;
        float centerY = getHeight() / 2;
        float radius = getResources().getDimensionPixelSize(R.dimen.radius);
        osCanvas.drawCircle(centerX, centerY, radius, paint);
    }

    @Override
    public boolean isInEditMode() {
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        bitmap = null; 
    }
}

CircleDrawActivity.java:

public class CircleDrawActivity  extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_draw);
    }
}

activity_circle_draw.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rlParent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/lighthouse"
        android:scaleType="fitXY" />

    <common.customview.CircleOverlayView
        android:id="@+id/cicleOverlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </common.customview.CircleOverlayView>


</RelativeLayout>

colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

dimens.xml:

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>

    <dimen name="radius">50dp</dimen>
</resources>

希望这会帮助你。

Hiren Patel answered 2020-02-14T01:46:16Z
32 votes

我找到了一种无需绘制和创建位图的解决方案。 这是我实施的结果:Example of overlay drawing

您需要使用Clear油漆创建自定义TutorialViewonDraw

    mBackgroundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

同样不要忘记禁用硬件加速并调用TutorialView,因为我们将覆盖onDraw方法

    setWillNotDraw(false);
    setLayerType(LAYER_TYPE_HARDWARE, null);

完整的示例在这里:

public class TutorialView extends FrameLayout {
    private static final float RADIUS = 200;

    private Paint mBackgroundPaint;
    private float mCx = -1;
    private float mCy = -1;

    private int mTutorialColor = Color.parseColor("#D20E0F02");

    public TutorialView(Context context) {
        super(context);
        init();
    }

    public TutorialView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TutorialView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TutorialView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        setWillNotDraw(false);
        setLayerType(LAYER_TYPE_HARDWARE, null);

        mBackgroundPaint = new Paint();
        mBackgroundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mCx = event.getX();
        mCy = event.getY();
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(mTutorialColor);
        if (mCx >= 0 && mCy >= 0) {
            canvas.drawCircle(mCx, mCy, RADIUS, mBackgroundPaint);
        }
    }
}

PS:此实现只是在其内部绘制一个孔,您需要在布局中放入背景,并在顶部添加此TutorialView

Oleksandr answered 2020-02-14T01:46:55Z
4 votes

@Robert的答案实际上向我展示了如何解决此问题,但是他的代码不起作用。 因此,我更新了他的解决方案并使之生效:

public class CaptureLayerView extends View {

  private Bitmap bitmap;
  private Canvas cnvs;
  private Paint p = new Paint();
  private Paint transparentPaint = new Paint();;
  private Paint semiTransparentPaint = new Paint();;
  private int parentWidth;
  private int parentHeight;
  private int radius = 100;

  public CaptureLayerView(Context context) {
      super(context);
      init();
  }

  public CaptureLayerView(Context context, AttributeSet attrs) {
      super(context, attrs);
      init();
  }

  private void init() {
      transparentPaint.setColor(getResources().getColor(android.R.color.transparent));
      transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

      semiTransparentPaint.setColor(getResources().getColor(R.color.colorAccent));
      semiTransparentPaint.setAlpha(70);
  }

  @Override
  protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);

      bitmap = Bitmap.createBitmap(parentWidth, parentHeight, Bitmap.Config.ARGB_8888);
      cnvs = new Canvas(bitmap);
      cnvs.drawRect(0, 0, cnvs.getWidth(), cnvs.getHeight(), semiTransparentPaint);
      cnvs.drawCircle(parentWidth / 2, parentHeight / 2, radius, transparentPaint);
      canvas.drawBitmap(bitmap, 0, 0, p);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

      parentWidth = MeasureSpec.getSize(widthMeasureSpec);
      parentHeight = MeasureSpec.getSize(heightMeasureSpec);

      this.setMeasuredDimension(parentWidth, parentHeight);
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }
}

现在,在以下任何布局中使用此视图:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<SurfaceView
    android:id="@+id/surfaceView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">
</SurfaceView>

<com.example.myapp.CaptureLayerView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<Button
    android:id="@+id/btnTakePicture"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:onClick="onClickPicture"
    android:text="@string/take_picture">
</Button>

在这里,我想在SurfaceView上设置一个半透明的图层,并在中间放置一个透明的圆圈。附言 这段代码不是经过优化的,因为它在onDraw方法中创建了位图,这是因为我无法在init方法中获得父视图的宽度和高度,所以我只能在onDraw中知道它们。

Yelnar answered 2020-02-14T01:47:24Z
1 votes

我没有太多要添加到您的答案中,但是,如果有人感兴趣,我将位图分配和所有内容都移到了onSizeChanged,因此在性能上更好。

在这里,您可以找到带有“孔”的FrameLayout;)

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;

/**
 * Created by blackvvine on 1/1/16.
 */
public class SteroidFrameLayout extends FrameLayout {

    private Paint transPaint;
    private Paint defaultPaint;

    private Bitmap bitmap;
    private Canvas temp;

    public SteroidFrameLayout(Context context) {
        super(context);
        __init__();
    }

    public SteroidFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        __init__();
    }

    public SteroidFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        __init__();
    }

    private void __init__() {
        transPaint = new Paint();
        defaultPaint = new Paint();
        transPaint.setColor(Color.TRANSPARENT);
        transPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        setWillNotDraw(false);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        temp = new Canvas(bitmap);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        temp.drawColor(Color.TRANSPARENT);
        super.dispatchDraw(temp);
        temp.drawCircle(cx, cy, getWidth()/4, transPaint);

        canvas.drawBitmap(bitmap, 0, 0, defaultPaint);

        if (p < 1)
            invalidate();
        else
            animRunning = false;

    }

}

ps:虽然比原始答案要有效得多,但在draw()方法中仍然是一项繁重的工作,因此,如果您在像我这样的动画中使用此技术,请不要指望60.0fps的平滑播放速度

Iman Akbari answered 2020-02-14T01:47:54Z
0 votes

这为我工作:

canvas.drawCircle(x,y,radius,new Paint(Color.TRANSPARENT))
max answered 2020-02-14T01:48:14Z
0 votes

如果您在背景不透明的视图上无法获得透明的圆形切口,请参阅此答案。 为了使其正常工作,我将自定义布局视图设置为在XML中具有透明背景,然后使用线条将所需的背景颜色绘制为线条

cv.drawColor(Color.BLUE); //replace with your desired background color

我在上面链接的答案中的完整OnDraw方法:

@Override
protected void onDraw(Canvas canvas) {

    int w = getWidth();
    int h = getHeight();
    int radius = w > h ? h / 2 : w / 2;

    bm.eraseColor(Color.TRANSPARENT);
    cv.drawColor(Color.BLUE);
    cv.drawCircle(w / 2, h / 2, radius, eraser);
    canvas.drawBitmap(bm, 0, 0, null);
    super.onDraw(canvas);
}
Jacob Hatwell answered 2020-02-14T01:52:57Z
0 votes
public class CircleBlur extends Activity implements View.OnTouchListener {
SeekBar seekBar;
ImageView image,image1;

private Paint paint;
Bitmap circle,blurimg;

private Matrix matrix = new Matrix();
private Matrix savedMatrix = new Matrix();
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private int mode = NONE;
private PointF start = new PointF();
private PointF mid = new PointF();
private float oldDist = 1f;
float newRot = 0f;
private float d = 0f;
private float[] lastEvent = null;
private float radius=12;
Bitmap blurbitmap;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_blurimage);
    image=findViewById(R.id.image);
    seekBar=findViewById(R.id.seekbar);
    image1=findViewById(R.id.image1);

    paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    //here your image bind to Imageview
    image.setImageResource(R.drawable.nas1);

    image1.setOnTouchListener(this);
    seekBar.setProgress(12);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            radius = (float) CircleBlur.this.seekBar.getProgress();
            blurbitmap=createBlurBitmap(blurimg, radius);
            CircleBlur();
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private Bitmap createBlurBitmap(Bitmap src, float r) {
    if (r <= 0) {
        r = 0.1f;
    } else if (r > 25) {
        r = 25.0f;
    }
    Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
    RenderScript renderScript = RenderScript.create(this);

    Allocation blurInput = Allocation.createFromBitmap(renderScript, src);
    Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);

    ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
    blur.setInput(blurInput);
    blur.setRadius(r);
    blur.forEach(blurOutput);

    blurOutput.copyTo(bitmap);
    renderScript.destroy();

    return bitmap;
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public void CircleBlur()
{
    Bitmap result;
    // your circle image
    circle = BitmapFactory.decodeResource(getResources(),R.drawable.cicleouter);
        result = Bitmap.createBitmap(blurimg.getWidth(), blurimg.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(result);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        paint.setDither(true);
        mCanvas.drawBitmap(blurimg,0,0, null);
        mCanvas.drawBitmap(circle, matrix, paint);
        paint.setXfermode(null);
    image1.setImageBitmap(result);
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public boolean onTouch(View v, MotionEvent event) {
        image1 = (ImageView) v;
        float x = event.getX(), y = event.getY();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(x, y);
                mode = DRAG;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;
            // case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    float dx = x - start.x;
                    float dy = y - start.y;
                    matrix.postTranslate(dx, dy);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        float scale = (newDist / oldDist);
                        matrix.postScale(scale, scale, mid.x, mid.y);
                    }
                    if (lastEvent != null && event.getPointerCount() == 2 || event.getPointerCount() == 3) {
                        newRot = rotation(event);
                        float r = newRot - d;
                        float[] values = new float[9];
                        matrix.getValues(values);
                        float tx = values[2];
                        float ty = values[5];
                        float sx = values[0];
                        float xc = (image.getWidth() / 2) * sx;
                        float yc = (image.getHeight() / 2) * sx;
                        matrix.postRotate(r, tx + xc, ty + yc);
                    }
                }
                break;
        }
    CircleBlur();
        return true;
}
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    float s=x * x + y * y;
    return (float)Math.sqrt(s);
}
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}
private float rotation(MotionEvent event) {
    double delta_x = (event.getX(0) - event.getX(1));
    double delta_y = (event.getY(0) - event.getY(1));
    double radians = Math.atan2(delta_y, delta_x);
    return (float) Math.toDegrees(radians);
}

}

Purushotham answered 2020-02-14T01:53:17Z
translate from https://stackoverflow.com:/questions/19947835/android-canvas-draw-transparent-circle-on-image