基本上,我有一个矩形位图,并希望创建一个新的具有平方尺寸的位图,其中包含矩形位图。
例如,如果源位图的宽度为100,高度为400,则需要一个宽度为400,高度为400的新位图。然后,在此新位图中心绘制源位图(请参见附图以获得更好的理解)。
我的代码可以成功创建正方形位图,但源位图没有被绘制进去。因此,我得到了一个完全是黑色的位图。
以下是代码:
例如,如果源位图的宽度为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();
}
你有什么想法,我做错了什么吗?