作家
登录

如何在Android App上高效显示位图

作者: 来源: 2017-05-09 15:05:52 阅读 我要评论

为了创建具有视觉魅力的app,显示图像是必须的。学会在你的Android app上高效地显示位图,而不是放弃机能。

在Android上显示图像的苦楚

当工作于开辟视觉魅力的app时,显示图像是必须的。问题是,Android操作体系不克不及很好地处理图像解码,大年夜而迫使开辟者要当心某些义务以避免搞乱机能。

Google写了一个有关于高效显示位图的完全指南,我们可以按照这个指南来懂得和解决在显示位图时Android操作体系的重要缺点。

Android app机能杀手

按照Google的指南,我们可以列出一些我们在Android apps上显示图像时碰到的重要问题。

降低图像采样率

无论视图大年夜小,Android老是解码并全尺寸/大年夜小显示图像。因为这个原因,所以如不雅你试图加载一个大年夜图像,那就很轻易使你的设备出现outOfMemoryError。

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,         int reqWidth, int reqHeight) {    // First decode with inJustDecodeBounds=true to check dimensions    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeResource(res, resId, options);    // Calculate inSampleSize    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);    // Decode bitmap with inSampleSize set    options.inJustDecodeBounds = false;    return BitmapFactory.decodeResource(res, resId, options);}

你可以手动设置inSampleSize,或应用显示器的尺寸计算。

public static int calculateInSampleSize(             BitmapFactory.Options options, int reqWidth, int reqHeight) {    // Raw height and width of image    final int height = options.outHeight;    final int width = options.outWidth;    int inSampleSize = 1;    if (height > reqHeight || width > reqWidth) {        final int halfHeight = height / 2;        final int halfWidth = width / 2;        // Calculate the largest inSampleSize value that is a power of 2 and keeps both        // height and width larger than the requested height and width.        while ((halfHeight / inSampleSize) >= reqHeight                && (halfWidth / inSampleSize) >= reqWidth) {            inSampleSize *= 2;        }    }    return inSampleSize;}

异步解码

即使在应用BitmapFactory时,图像解码在UI线程上完成。这可以冻结app,并导致ANR(“Application Not Responding应用法度榜样没有响应”)戒备。

这个轻易解决,你只须要将解码过程放到工作线程上。一种办法是应用异步义务,正如Google指导中解释的那样:

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {    private final WeakReference<ImageView> imageViewReference;    private int data = http://mobile.51cto.com/0;    public	
				
			

  推荐阅读

  你以为人工智能真能超越人类?大错特错!

【AI世代编者按】美国《连线》杂志开创主编凯文-凯利(Kevin Kelly)日前撰文,阐述了当今社会对人工智能的五大年夜误会,并对背后的逻辑和理论展开了具体阐述。以下为文┞仿全文:我听到>>>详细阅读


本文标题:如何在Android App上高效显示位图

地址:http://www.17bianji.com/lsqh/35095.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)