Hen*_*que 6 android bitmap android-layout android-canvas
基本上,我有一个矩形位图,并希望创建一个方形尺寸的新位图,其中包含矩形位图.
因此,例如,如果源位图的宽度为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();
}
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
ser*_*y.n 15
试试这个:
private static Bitmap createSquaredBitmap(Bitmap srcBmp) {
int dim = Math.max(srcBmp.getWidth(), srcBmp.getHeight());
Bitmap dstBmp = Bitmap.createBitmap(dim, dim, Config.ARGB_8888);
Canvas canvas = new Canvas(dstBmp);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(srcBmp, (dim - srcBmp.getWidth()) / 2, (dim - srcBmp.getHeight()) / 2, null);
return dstBmp;
}
Run Code Online (Sandbox Code Playgroud)
哎呀,刚刚意识到问题是什么。我画错Bitmap了Canvas。如果它对将来的任何人有帮助,请记住 Canvas 已经附加,并将绘制到您在其构造函数中指定的位图。所以基本上:
这:
c.drawBitmap(resultBitmap, sourceRect, destinationRect, null);
Run Code Online (Sandbox Code Playgroud)
实际上应该是:
c.drawBitmap(sourceBitmap, sourceRect, destinationRect, null);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7888 次 |
| 最近记录: |