对于我的答案,我正在绘制一个较小的Bitmap
到较大的Bitmap
,然后将其绘制到SurfaceView
。
- 使用边界四边形创建边界矩形。
- 使用边框创建一个转换
Matrix
- 使用
Matrix.ScaleToFit.CENTER
填充边界矩形的最大尺寸可能较小Bitmap
。
在完成这些步骤之后,只需在画布上画出更大的Bitmap
即可使用。边界四边形绘制为红色,边界矩形为蓝色,大Bitmap
绘制为绿色。将小号Bitmap
替换为蓝色Bitmap
(边界矩形)。
public class MainActivity extends Activity {
final String TAG = this.getClass().getName();
SurfaceView surfaceView;
Bitmap bitmap;
Bitmap bigBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback2() {
@Override
public void surfaceRedrawNeeded(SurfaceHolder holder) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas surfaceCanvas = holder.lockCanvas();
surfaceCanvas.drawBitmap(bigBitmap, 0, 0, new Paint());
holder.unlockCanvasAndPost(surfaceCanvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
bitmap = Bitmap.createBitmap(64, 192, Bitmap.Config.ARGB_8888);
{
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(0, 0, 64, 192, paint);
}
bigBitmap = Bitmap.createBitmap(768,768, Bitmap.Config.ARGB_8888);
{
Canvas canvas = new Canvas(bigBitmap);
// Fill background - For visual reference
Paint paint = new Paint();
paint.setColor(Color.GREEN);
canvas.drawRect(0, 0, bigBitmap.getWidth(), bigBitmap.getHeight(), paint);
// Setup transformation
Matrix matrixPoly = new Matrix();
Log.i(TAG, "matrixPoly: " + matrixPoly);
// Draw Quadrilateral - For visual reference
boolean canScale;
canScale = matrixPoly.setPolyToPoly(new float[]{0,0, 64,0, 0,192, 64,192},
0,
new float[]{32,32, 96,16, 16,300, 128,256},
0,
4);
Log.i(TAG, "matrixPoly: " + matrixPoly);
Log.i(TAG, "matrixPoly canScale: " + canScale);
canvas.drawBitmap(bitmap, matrixPoly, new Paint());
// Points of Quadrilateral
// {32,32, 96,16, 16,300, 128,256}
float rectInQLeft = Math.max(32, 16);
float rectInQTop = Math.min(32, 16);
float rectInQRight = Math.min(96, 128);
float rectInQBottom = Math.max(300, 256);
;
Matrix matrixRect = new Matrix();
Log.i(TAG, "matrixRect: " + matrixRect);
canScale = matrixRect.setRectToRect(new RectF(0, 0, 64, 192),
new RectF(rectInQLeft, rectInQTop, rectInQRight, rectInQBottom),
Matrix.ScaleToFit.CENTER);
Log.i(TAG, "matrixRect: " + matrixRect);
Log.i(TAG, "matrixRect canScale: " + canScale);
// Draw scaled bitmap
Canvas smallBitmapCanvas = new Canvas(bitmap);
Paint smallBitmapPaint = new Paint();
smallBitmapPaint.setColor(Color.BLUE);
smallBitmapCanvas.drawRect(0, 0, 64, 192, smallBitmapPaint);
canvas.drawBitmap(bitmap, matrixRect, new Paint());
}
}
请参阅Matrix.setPolyToPoly – pskink