有没有一种方法来加载和文件在Android中画出部分的位图? [英] Is there a way to load and draw partially a bitmap from file in Android?

查看:90
本文介绍了有没有一种方法来加载和文件在Android中画出部分的位图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有磁盘上的一个有点大(即不适合大多数手机的内存)的位图。我希望在不进行缩放的方式画出它只有部分在屏幕上(即 inSampleSize == 1

Say I have a somewhat large (i.e. not fit in most phones' memory) bitmap on disk. I want to draw only parts of it on the screen in a way that isn't scaled (i.e. inSampleSize == 1)

有没有一种方式来加载/画只是我想给一方的矩形无需加载整个位图的内容指定的区域?

Is there a way to load/draw just the part I want given a Rect specifying the area without loading the entire bitmap content?

推荐答案

我非常有信心,这是可能的,因为你可以加载一个非常大的位图文件到一个的ImageView 没有问题,所以必须有某种形式的内置的方式来处理大位图......并经过几次尝试,我已经找到了解决办法:

I'm quite confident this is possible since you can load a really large bitmap file into an ImageView without problems so there must be some sort of a built-in way to handle large bitmaps... and after a few attempts, I've found a solution:

不必加载整个位图和手工自己绘制它,装载它的绘制对象来代替:

Instead of loading the entire bitmap and manually draw it yourself, load it as a Drawable instead:

InputStream mapInput = getResources().openRawResource(
        R.drawable.transit_map);
_map = Drawable.createFromStream(mapInput, "transit_map");

_map.setBounds(0, 0, _mapDimension.width(), _mapDimension.height());

我使用的资源文件,但因为你可以用 Drawable.createFromStream 来加载任何图像的InputStream ,它应该适用于任意的位图。

I'm using a resource file but since you can use Drawable.createFromStream to load image from any InputStream, it should works with arbitrary bitmap.

然后,使用 Drawable.draw 方法来绘制到像这样的期望的画布:

Then, use the Drawable.draw method to draw it onto the desired canvas like so:

int left = -(int) contentOffset.x;
int top = -(int) contentOffset.y;
int right = (int) (zoom * _mapDimension.width() - contentOffset.x);
int bottom = (int) (zoom * _mapDimension.height() - contentOffset.y);

_map.setBounds(left, top, right, bottom);
_map.draw(canvas);

如在上述情况下,您还可以通过操作可绘制的边界和位图的只有相关的部分缩放和转换位图也将被加载并绘制到画布

As in the above case, You can also scale and translate the bitmap as well by manipulating the drawable's bounds and only the relevant parts of the bitmap will be loaded and drawn onto the Canvas.

其结果是只从一个单一的200KB位图文件的夹可缩放图。我还测试了这款带有22MB PNG文件,它仍然有效,没有任何的OutOfMemoryError 包括当屏幕方向的变化。

The result is a pinch-zoomable view from just one single 200KB bitmap file. I've also tested this with a 22MB PNG file and it still works without any OutOfMemoryError including when screen orientation changes.

这篇关于有没有一种方法来加载和文件在Android中画出部分的位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆