您可以使用BitmapRegionDecoder
来分解较大的位图(需要API级别10)。 我编写了一个将利用此类并返回可放置在 ImageView
中的单个Drawable
的方法:
private static final int MAX_SIZE = 1024;
private Drawable createLargeDrawable(int resId) throws IOException {
InputStream is = getResources().openRawResource(resId);
BitmapRegionDecoder brd = BitmapRegionDecoder.newInstance(is, true);
try {
if (brd.getWidth() <= MAX_SIZE && brd.getHeight() <= MAX_SIZE) {
return new BitmapDrawable(getResources(), is);
}
int rowCount = (int) Math.ceil((float) brd.getHeight() / (float) MAX_SIZE);
int colCount = (int) Math.ceil((float) brd.getWidth() / (float) MAX_SIZE);
BitmapDrawable[] drawables = new BitmapDrawable[rowCount * colCount];
for (int i = 0; i < rowCount; i++) {
int top = MAX_SIZE * i;
int bottom = i == rowCount - 1 ? brd.getHeight() : top + MAX_SIZE;
for (int j = 0; j < colCount; j++) {
int left = MAX_SIZE * j;
int right = j == colCount - 1 ? brd.getWidth() : left + MAX_SIZE;
Bitmap b = brd.decodeRegion(new Rect(left, top, right, bottom), null);
BitmapDrawable bd = new BitmapDrawable(getResources(), b);
bd.setGravity(Gravity.TOP | Gravity.LEFT);
drawables[i * colCount + j] = bd;
}
}
LayerDrawable ld = new LayerDrawable(drawables);
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
ld.setLayerInset(i * colCount + j, MAX_SIZE * j, MAX_SIZE * i, 0, 0);
}
}
return ld;
}
finally {
brd.recycle();
}
}
该方法将检查可绘制资源在两个轴上是否小于MAX_SIZE
(1024)。如果是,则只返回可绘制资源。如果不是,则会将图像拆分并解码图像块,并将它们放置在LayerDrawable
中。
我选择了1024,因为我相信大多数可用手机都支持至少那么大的图像。如果您想找到手机的实际纹理大小限制,您需要通过OpenGL进行一些奇怪的操作,而这不是我想深入研究的内容。
我不确定您如何访问您的图像,所以我假设它们在您的drawable文件夹中。如果不是这种情况,那么重构该方法以接受您需要的任何参数应该相对容易。