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

pbpqsu0x  于 2022-11-03  发布在  Android
关注(0)|答案(3)|浏览(233)

基本上,我有一个矩形位图,并希望创建一个新的位图与平方尺寸将包含矩形位图内。
因此,例如,如果源位图的宽度为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();
}

你知道我做错了什么吗

jei2mxaa

jei2mxaa1#

试试看:

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

blmhpbnm2#

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

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

实际上应该是:

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

myss37ts3#

/**
 * 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
}

相关问题