如何在Android中从矩形位图创建正方形位图

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

你有什么想法,我做错了什么吗?


你为什么要使用画布而不是 ImageView? - dumazy
3个回答

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

帮了我很多..谢谢 - sathya

2

糟糕,我刚意识到问题所在。我错误地将错误的Bitmap绘制到了Canvas上。如果有帮助到未来的任何人,请记住Canvas已经附加并会绘制到您在其构造函数中指定的位图上。所以基本上:

这个:

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

应该实际上是:

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

0
/**
 * Add a shape to bitmap.
 */
fun addShapeToBitmap(originBitmap: Bitmap): Bitmap {

    val stream = ByteArrayOutputStream()

    // **create RectF for a rect shape**
    val rectF = RectF()
    rectF.top = originBitmap.height / 2f - 100f
    rectF.bottom = originBitmap.height / 2f + 100f
    rectF.left = originBitmap.width / 2f - 100f
    rectF.right = originBitmap.width / 2f + 100f

    // **create a new bitmap which is an empty bitmap**
    val newBitmap = Bitmap.createBitmap(originBitmap.width, 
    originBitmap.height, originBitmap.config)
    // **create a canvas and set the empty bitmap as the base layer**
    val canvas = Canvas(newBitmap)
    // **draw the originBitmap on the first laye
    canvas.drawBitmap(originBitmap, 0f, 0f, null)
    // **draw the shape on the second layer**
    // **the second layer cover on the first layer**
    canvas.drawRect(rectF, paint)
    newBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
    newBitmap.recycle()
    return newBitmap
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接