android ---Drawable Mutations笔记

原文来自Android SDK文档中的 resources/articles/drawable-mutations.html

在Android中有大量的图片加载,Android性能优化其加载过程,也就是说在每一个加载的drawable添加一个共享状态。

虽然共享状态能够节约很多内存,但是同样也会带来对图片修改带来一些麻烦。

Android在图片中添加了一个共享的状态图.如下:

从代码上来看

getDrawable().mutate();

 /**
     * Make this drawable mutable. This operation cannot be reversed. A mutable
     * drawable is guaranteed to not share its state with any other drawable.
     * This is especially useful when you need to modify properties of drawables
     * loaded from resources. By default, all drawables instances loaded from
     * the same resource share a common state; if you modify the state of one
     * instance, all the other instances will receive the same modification.
     *
     * Calling this method on a mutable Drawable will have no effect.
     *
     * @return This drawable.
     * @see ConstantState
     * @see #getConstantState()
     */

/ **
     *将此绘制可变的。此操作无法逆转。一个可变
     *提拉是保证不与任何其他可拉伸共享其状态。
     *当你需要修改的可绘性质,这是特别有用
     *从资源加载。默认情况下,所有的可绘实例从装
     *相同的资源共享共同的状态;如果您修改一个状态
     *实例中,所有的其他实例将接收相同的修饰。
     *
     *调用一个可变的可绘制这种方法不会有任何效果。
     *
     返回:此绘制。
     *@see ConstantState
     *@see#getConstantState()
     * /

也就是说,如果你多个页面都共用了这个图片,那么你可以通过这个mutate()方法获得一个与这个相同的图片,然后可以对此处进行处理。


例如:

在listview中如果运用了评分的控件;(共用一张图的情况)

没使用共享状态


  1. Drawable star = context.getResources().getDrawable(R.drawable.star);  
  2. if (book.isFavorite()) {  
  3.   star.setAlpha(255); // opaque  
  4. else {  
  5.   star.setAlpha(70); // translucent  
  6. }  
此时一处修改,多处修改.

使用了共享状态:


  1. Drawable star = context.getResources().getDrawable(R.drawable.star);  
  2. if (book.isFavorite()) {  
  3.   star.mutate().setAlpha(255); // opaque  
  4. else {  
  5.   star. mutate().setAlpha(70); // translucent  
  6. }  






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值