基本上,我有一个矩形位图,并想创建一个具有平方尺寸的新位图,其中将包含矩形位图。
因此,例如,如果源位图的宽度:100 和高度:400,我想要一个宽度:400 和高度:400 的新位图。然后,在这个新位图的中心绘制源位图(请参阅附图以获得更好的理解)。
我下面的代码可以很好地创建方形位图,但没有将源位图绘制到其中。结果,我留下了一个完全黑色的位图。
这是代码:
Bitmap sourceBitmap = BitmapFactory.decodeFile(sourcePath);
Bitmap resultBitmap= Bitmap.createBitmap(sourceBitmap.getHeight(), sourceBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(resultBitmap);
Rect sourceRect = new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight());
Rect destinationRect = new Rect((resultBitmap.getWidth() - sourceBitmap.getWidth())/2, 0, (resultBitmap.getWidth() + sourceBitmap.getWidth())/2, sourceBitmap.getHeight());
c.drawBitmap(resultBitmap, sourceRect, destinationRect, null);
// save to file
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
File file = new File(mediaStorageDir.getPath() + File.separator + "result.jpg");
try {
result.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
知道我做错了什么吗?