Android Canvas焦点在选定区域

时间:2016-12-21 11:28:56

标签: android canvas bitmap paint

我正试图达到这个效果:

enter image description here

我的想法是,我希望用ImageView覆盖部分透明层,但不是全部。某处有一个区域(圆形或矩形),应该是完全透明的。我用这行代码尝试了它:

Paint paint = new Paint();
paint.setColor(Color.parseColor("#80000000"));
canvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), paint);
paint.setColor(Color.TRANSPARENT);
canvas.drawCircle((int) x, (int) y, 50, paint);

但它不起作用,因为在圆圈下面有矩形。 无论如何要实现我想要的目标吗?

1 个答案:

答案 0 :(得分:0)

对不起,迟到了。 你可以实现这个我的CustomImageView,并按照以下步骤进行。

public class CustomImageView extends ImageView {

private Paint paint;
private Paint transParentPaint;
private Canvas tempCanvas;
private Bitmap emptyBitmap;

public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

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

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

private void init() {
    paint = new Paint();
    paint.setColor(Color.parseColor("#80000000"));  //Semi TransParent Paint

    transParentPaint = new Paint();
    transParentPaint.setColor(Color.TRANSPARENT);
    transParentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));//This is necessary to make the portion transparent. Otherwise it will show Black.
}


@Override
protected void onDraw(Canvas canvas) {
    emptyBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    tempCanvas = new Canvas(emptyBitmap);
    emptyBitmap.eraseColor(Color.TRANSPARENT);
    // tempCanvas.drawColor(Color.parseColor("#80000000"));
    tempCanvas.drawRect(0, 0, getWidth(), getHeight(), paint);
    tempCanvas.drawCircle(getWidth() / 2, getHeight() / 2, 100, transParentPaint); // Set the circle at the middle of the Canvas.
    canvas.drawBitmap(emptyBitmap, 0, 0, null);
}

}

将此CustomImageView添加到布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
>

<transparent.example.com.partialtransparentview.CustomImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/your_image" />
</RelativeLayout>

它会按预期工作。