简体   繁体   English

内存与性能,哪个最好?

[英]Memory vs Performance, which would be best?

I need to take an image, scale it, mask it, add a background in case some of it is transparent and then add an overlay image. 我需要拍摄图像,缩放比例,遮罩它,添加背景(以防某些背景透明),然后添加覆盖图像。 To do this I've written the following: 为此,我编写了以下内容:

Canvas canvas = new Canvas();
Bitmap mainImage = Bitmap.createScaledBitmap(((BitmapDrawable)d).getBitmap(), iconSize, iconSize, false);
Bitmap result = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);

canvas.setBitmap(result);
Paint paint = new Paint();
paint.setFilterBitmap(false);

Bitmap mask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.res, context.mask_bg)
                    , iconSize, iconSize, false);
                        canvas.drawBitmap(mask, 0, 0, paint);
canvas.drawBitmap(mainImage, 0, 0, paint);

mask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.res, context.mask)
                    , iconSize, iconSize, false);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(mask, 0, 0, paint);

mask = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.res, context.mask_frame)
                    , iconSize, iconSize, false);
paint.setXfermode(null);
canvas.drawBitmap(mask, 0, 0, paint);

Now this operation is going to happen alot in my application. 现在,此操作将在我的应用程序中大量发生。 And my application always has a service running (which is the context in this case). 而且我的应用程序始终在运行服务(在本例中为上下文)。 I don't know too much about performance when it comes to images and I know they use up to 4 times their actual size in space but this seems like a waste to me recreating the same objects over and over. 我对图像的性能并不了解太多,我知道它们使用的空间是其实际大小的四倍,但这对于我一次又一次地重新创建相同的对象来说似乎是浪费。 Plus the main need for my app is performance over size. 再加上我的应用程序的主要需求是性能超过大小。

So I'm wondering is it better to keep the bitmaps being generated each time in the service so they're only created once (only the mainImage bitmap will change each time) or even as a drawable create the bitmap from that? 因此,我想知道将每次生成的位图都保留在服务中是否更好,以便它们仅创建一次(每次仅更改mainImage位图),还是作为可绘制对象从中创建位图?

Never conserve a drawable outside of the activity/fragment where it is displayed. 切勿在可显示活动/片段的外部保存可绘制对象。
It can very easily create memory leaks : the drawable keep a reference to its activity, so the garbage collector can not destroy it, even if it has been destroyed and recreated since. 它很容易造成内存泄漏:可绘制对象保留对其活动的引用,因此垃圾收集器无法销毁它,即使此后它已被销毁并重新创建。
Use bitmaps instead. 请改用位图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM