【问题标题】:Clear/Reset entire ImageView canvas清除/重置整个 ImageView 画布
【发布时间】:2021-05-01 14:49:20
【问题描述】:

我有一个带有 2 个 imageViews 的简单布局:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:id="@+id/takenPicture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
     />

     <com.example.dochjavatestimplementation.pkgActivity.ExtendedImageView
        android:id="@+id/takenPicture2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
      />
    
</RelativeLayout>

第一个 ImageView 显示一个位图,第二个 ImageView (1) 是自定义的 ImageView (ExtendedImageView) (2) 它绘制了一个显示在普通 ImageView 之上的画布。 这看起来像这样: displayimageviews

我想要的是在我的onDraw 方法中绘制矩形后,我想再次清除矩形(现在只是为了测试目的)。这是我的代码的样子:

@Override
protected void onDraw(Canvas canvas) {

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(3);
    canvas.drawRect(new Rect(212,0,-720,600),paint);
    
    //clear the rect/contents of canvas again
    //try 1
    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY);
    canvas.drawColor(0, PorterDuff.Mode.CLEAR);

    //try2
    Paint transparent = new Paint();
    transparent.setAlpha(0);
    canvas.drawPaint(transparent);

    //try3
    setImageResource(0);
}

我尝试以三种不同的方式清除画布/矩形,如上面的代码所示,但它不会改变输出,因为黑色矩形仍然可见。 我现在的问题是原因可能是什么?是因为我没有“更新”画布,还是因为我尝试清除画布?

结果基本上应该是我只看到了第一个imageview

【问题讨论】:

    标签: android canvas android-imageview android-drawable ondraw


    【解决方案1】:

    View.onDraw() 在 Canvas 上绘制形状是低级函数,在最后阶段直接改变显示上的像素。所以,一旦你画了东西,就不可能抹去它。它没有缓冲。屏幕上只剩下混合的 RGB(无 A)像素。以前的像素颜色(源自“takenPicture”)已经丢失。

    如果您想让形状可擦除,请准备另一个由 ARGB 位图支持的画布并在其上绘制所有内容。最后在画布上绘制位图。

    @Override
    protected void onDraw(Canvas canvas)
    {
    
        // Prepare Bitmap and Canvas 
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas draw_canvas = new Canvas(bitmap);
    
        // Draw a rect.
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        draw_canvas.drawRect(new Rect(212,0,-720,600),paint);
    
        // Clear
        draw_canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.SRC);
    
        // Draw the bitmap.
        canvas.drawBitmap(bitmap, 0, 0, null);
        bitmap.recycle();
    }
    

    【讨论】:

    • 是否有一些“更清洁”的方式来处理绘图等?还是重写 ondraw 是唯一的选择?
    • 由于不清楚你将如何发展它,所以很难给你具体的答案。但总的来说,创建custom Drawable class 可能是常见的做法。如果性能无关紧要,则不需要使用位图来缓存图形。请参阅Drawable documentation 并找到满足您要求的解决方案。
    猜你喜欢
    • 2013-09-14
    • 2012-11-26
    • 2012-03-14
    • 2018-07-25
    • 2017-06-21
    • 2012-07-26
    • 2012-07-19
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多