9

基本上,我有一个矩形位图,并想创建一个具有平方尺寸的新位图,其中将包含矩形位图。

因此,例如,如果源位图的宽度: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();
}

知道我做错了什么吗?

4

2 回答 2

20

试试这个:

    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;
    }
于 2014-05-22T13:59:35.627 回答
2

哎呀,才意识到问题出在哪里。我画错BitmapCanvas。如果它对将来的任何人有帮助,请记住 Canvas 已经附加,并将绘制到您在其构造函数中指定的位图。所以基本上:

这:

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

实际上应该是:

c.drawBitmap(sourceBitmap, sourceRect, destinationRect, null);
于 2013-11-02T19:34:02.940 回答