从位图无效的创建或剪切6个相等的部分

时间:2013-12-27 06:07:30

标签: android view bitmap

在我的应用程序中,我有一个方法可以从给定的位图中删除6个相等的部分。它适用于方形的位图,但不适用于矩形位图。

这是方法。

public Bitmap[] splitBitmap6(Bitmap picture) {
    int w = picture.getWidth();
    int h = picture.getHeight();
    Bitmap scaledBitmap = null;

    int widthofmainBitMap  = screenWidth ;
    int heightofmainBitMap = widthofmainBitMap*h/w;

    scaledBitmap = Bitmap.createScaledBitmap(picture, widthofmainBitMap, heightofmainBitMap, true);

    Bitmap[] imgs = new Bitmap[];

    imgs[0] = Bitmap.createBitmap(scaledBitmap, 0, 0, picture.getWidth()/3 , picture.getHeight()/2);
    imgs[1] = Bitmap.createBitmap(scaledBitmap, picture.getWidth()/3, 0, picture.getWidth()/3,picture.getHeight()/2);
// i get the error at this line

    imgs[2] = Bitmap.createBitmap(scaledBitmap,((picture.getWidth()/3)+(picture.getWidth()/3)), 0, picture.getWidth()/3,picture.getHeight()/2);
    imgs[3] = Bitmap.createBitmap(scaledBitmap, 0, (picture.getHeight()/2), picture.getWidth()/3, picture.getHeight()/2);
    imgs[4] = Bitmap.createBitmap(scaledBitmap, picture.getWidth()/3, picture.getHeight()/2, picture.getWidth()/3,picture.getHeight()/2);
    imgs[5] = Bitmap.createBitmap(scaledBitmap, (picture.getWidth()/3)+(picture.getWidth()/3), picture.getHeight()/2,picture.getWidth()/3,picture.getHeight()/2);

    return imgs;
}

我收到错误:

java.lang.illegalargumentexception: x + width must be <= bitmap.width.

1 个答案:

答案 0 :(得分:2)

问题是您使用的是picture.getWidth()picture.getHeight()。但是,您已缩放picture并将其存储在scaledBitmap

picture的尺寸与scaledBitmap的尺寸不同。因此抛出了上述异常。

您应该使用:scaledBitmap.getWidth()scaledBitmap.getHeight()代替。

另外:

按如下方式设置picture = scledBitmap

...
...
scaledBitmap = Bitmap.createScaledBitmap(picture, widthofmainBitMap, heightofmainBitMap, true);
picture = scaledBitmap;
...
...
// rest remains same