Canvas.drawBitmap()方法绘图空白

问题出现的场景:

将一个ImageView上原有的Bitmap进行放缩操作后,重新设置到该ImageView上。放缩部分代码如下:

private void bitmapScale(float x,float y){
    Bitmap newBitmap = Bitmap.createBitmap((int) (mBitmap.getWidth() * x),(int) (mBitmap.getHeight() * y), mBitmap.getConfig());
    Canvas canvas = new Canvas(newBitmap);
    Matrix matrix = new Matrix();
    matrix.setScale(x, y);
    canvas.drawBitmap(newBitmap, matrix, mPaint);
    imageView.setImageBitmap(newBitmap);
}

其中mBitmap是ImageView上原有的Bitmap,实际运行的效果是原来的图消失了,放缩之后的图没有出现,显示为空白。

解决办法:

在最后canvas绘图的方法中,第一个参数应该传入mBitmap而不是newBitmap

canvas.drawBitmap(mBitmap, matrix, mPaint);

原因分析:

看下drawBitmap()方法的参数定义:

/**
 * Draw the bitmap using the specified matrix.
 *
 * @param bitmap The bitmap to draw
 * @param matrix The matrix used to transform the bitmap when it is drawn
 * @param paint May be null. The paint used to draw the bitmap
 */
public void drawBitmap(@NonNull Bitmap bitmap, @NonNull Matrix matrix, @Nullable Paint paint) {
    super.drawBitmap(bitmap, matrix, paint);
}

显然,该方法通过明确的矩阵变换去绘制指定的bitmap,而待绘制的bitmap就是我们第一个参数,因此需要传入原有的图片(因为我们是对原图片进行操作的)。那么为啥错传newBitmap是空白呢?再来看看Bitmap.createBitmap()方法的定义:

/**
 * Returns a mutable bitmap with the specified width and height.  Its
 * initial density is as per {@link #getDensity}. The newly created
 * bitmap is in the {@link ColorSpace.Named#SRGB sRGB} color space.
 *
 * @param width    The width of the bitmap
 * @param height   The height of the bitmap
 * @param config   The bitmap config to create.
 * @throws IllegalArgumentException if the width or height are <= 0, or if
 *         Config is Config.HARDWARE, because hardware bitmaps are always immutable
 */
public static Bitmap createBitmap(int width, int height, @NonNull Config config) {
    return createBitmap(width, height, config, true);
}

可以看出该方法返回的是一个指定了宽高的可变位图,但它并没有绘制的实际内容,因此传入它作为第一参数时,看起来就是空白的。

猜你喜欢

转载自blog.csdn.net/Ein3614/article/details/82182735