自动缩放画布以适应位图

3
在我的自定义视图的OnDraw方法中,我使用Bitmap绘制到Canvas的中心位置。
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Rect r = canvas.getClipBounds();
    displayWidth = r.right;
    displayHeight = r.bottom;
    camera.applyToCanvas(canvas);
    float zW = (float)bitmapWidth / (float)displayWidth;
    float zH = (float)bitmapHeight / (float)displayHeight;
    float z = 0.0f;
    if (zW>1 || zH>1) {
        z = Math.max(zW, zH); 
    }
    canvas.drawColor(Color.DKGRAY);
    canvas.drawBitmap(bitmap, (displayWidth/2.0f - (bitmapWidth)/2.0f), (displayHeight/2.0f - bitmapHeight/2.0f), paint);
    if (z>0) {
        camera.translate(z, -z, z);
    }
}

如果Bitmap的高度或宽度大于Canvas大小(displayWidth, displayHeight),我该如何使用Camera类自动缩放以适应Bitmap并将其居中到Canvas中。有什么想法吗?
1个回答

0
尝试创建一个矩阵实例并使用以下方式进行初始化: public boolean setRectToRect (RectF src, RectF dst, Matrix.ScaleToFit stf)
只需执行一次此操作并将矩阵保留在内存中。请注意,Matrix.ScaleToFit 定义了 CENTER 值。
稍后绘制位图时,请使用以下版本的 drawBitmap: public void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接