【问题标题】:Cannot crop Bitmap无法裁剪位图
【发布时间】:2012-06-01 19:03:58
【问题描述】:

我正在尝试裁剪和缩放给定的位图,但只有缩放有效。
我做错了什么?

private Bitmap CropAndShrinkBitmap(Bitmap io_BitmapFromFile, int i_NewWidth, int i_NewHeight) 
{
    int cuttingOffset = 0;
    int currentWidth = i_BitmapFromFile.getWidth();
    int currentHeight = i_BitmapFromFile.getHeight();

    if(currentWidth > currentHeight)
    {
        cuttingOffset = currentWidth - currentHeight;
        Bitmap.createBitmap(i_BitmapFromFile, cuttingOffset/2, 0, currentWidth - cuttingOffset, currentHeight);
    }
    else
    {
        cuttingOffset = i_NewHeight - currentWidth;
        Bitmap.createBitmap(i_BitmapFromFile, 0, cuttingOffset/2, currentWidth, currentHeight - cuttingOffset);
    }
    Bitmap fixedBitmap = Bitmap.createScaledBitmap(i_BitmapFromFile, i_NewWidth, i_NewHeight, false)  ;

    return i_BitmapFromFile;
}

描述说:“createBitmap 返回一个不可变的位图”。
那什么意识?这是我的问题的原因吗?

【问题讨论】:

    标签: java android


    【解决方案1】:

    裁剪可能工作正常,但是被裁剪的结果 Bitmap 对象是从 createBitmap()返回,原始对象没有被修改(如前所述,因为 Bitmap 实例是不可变的)。如果你想要裁剪的结果,你必须获取返回值。

    Bitmap cropped = Bitmap.createBitmap(i_BitmapFromFile, cuttingOffset/2, 0, currentWidth - cuttingOffset, currentHeight);
    

    然后,您可以根据该结果进行任何进一步的工作。

    HTH

    【讨论】:

      【解决方案2】:

      默认情况下位图是“不可变的”,这意味着您无法更改它们。您需要创建一个可编辑的“可变”位图。

      查看以下链接了解如何操作:

      BitmapFactory.decodeResource returns a mutable Bitmap in Android 2.2 and an immutable Bitmap in Android 1.6

      http://sudarnimalan.blogspot.com/2011/09/android-convert-immutable-bitmap-into.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 1970-01-01
        • 2015-12-11
        • 2013-03-25
        • 2011-05-29
        • 2015-05-05
        • 1970-01-01
        相关资源
        最近更新 更多