如何从Android中一个矩形位图上创建一个正方形的位图 [英] How to create a square bitmap from a rectangular bitmap in Android

查看:218
本文介绍了如何从Android中一个矩形位图上创建一个正方形的位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个长方形的位图,并想创建一个平方维度的新位图,其中将包含它里面的矩形位图。

Basically, I have a rectangular bitmap and want to create a new Bitmap with squared dimensions which will contain the rectangular bitmap inside of it.

因此​​,例如,如果源位图具有宽度:100和高度:400,我想与宽度新位图:400和高度:400。然后,得出这样的新位图的中心内源位图(见更好地了解附加的图像)。

So, for example, if the source bitmap has width:100 and height:400, I want a new bitmap with width:400 and height:400. Then, draw the source bitmap centered inside of this new bitmap (see attached image for a better understanding).

我下面的code创建位图广场罚款,但源位图不被吸引进去。这样一来,我留下了一个位图,它是全黑的。

My code below creates the square bitmap fine, but the source bitmap is not being drawn into it. As a result, I'm left with a bitmap that is completely black.

下面是code:

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();
}

任何想法,我做错了吗?

Any idea what I'm doing wrong?

推荐答案

哎呦,刚刚意识到的问题是什么。我画错了位图画布。如果它可以帮助任何人在未来,请记住,画布是已经连接,并绘制你在其构造指定位图。所以基本上:

Whoops, just realized what the problem is. I was drawing the wrong Bitmap to the Canvas. If it helps anyone in the future, remember that the Canvas is already attached and will paint to the bitmap you specify in its constructor. So basically:

c.drawBitmap(resultBitmap, sourceRect, destinationRect, null);

实际上应该是:

c.drawBitmap(sourceBitmap, sourceRect, destinationRect, null);

这篇关于如何从Android中一个矩形位图上创建一个正方形的位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆