[关闭]
@act262 2017-03-15T11:20:40.000000Z 字数 1634 阅读 1044

使用图片的一些优化姿势

Android


需要了解的知识

图片内存占用计算

系统默认用Bitmap.Config.ARGB_8888加载图片,每个像素需要4个字节来存储,
所以16*16像素的图片占用内存就是16 * 16 * 4 = 1024 Byte = 1 KB
也就是64*64像素要16KB,160*160像素要100KB...

Bitmap占用内存和图片的体积不是正相关的,图片有压缩率,可以压的很小,但是加载到内存时是需要还原到每一个像素的,所以图片体积小不等于占用内存少.

减少内存占用

减小图片像素

降低图片质量

使用webP、jpg、矢量图

减少图片数量

  1. 图片基本一样,纯粹是颜色不同的情况下,不同状态的Drawable使用多套不同图
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <item android:drawable="@mipmap/ic_menu_normal" android:state_pressed="false" />
  4. <item android:drawable="@mipmap/ic_menu_pressed" android:state_pressed="true" />
  5. </selector>

改进方式:使用tint着色模式,减少多套不同颜色的图片

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <item android:state_pressed="true">
  4. <bitmap android:src="@mipmap/ic_menu_normal" android:tint="#D2B978" />
  5. </item>
  6. <item android:drawable="@mipmap/ic_menu_normal" />
  7. </selector>

限制:API >= 21(Android L)以后才原生支持tint着色
兼容:使用DrawableCompat,ViewCompat方法代码动态设置

ImageView可以使用tint着色修改图片的颜色,支持API>=9,详细参看使用 ImageView tint 属性

  1. <!-- API 21 以下只支持单色 -->
  2. <ImageView
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:tint="#f00"
  6. android:src="@mipmap/ic_search" />
  7. <!-- tint 使用多状态颜色(ColorStateList),API<21 不支持,会Crash -->
  8. <ImageView
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:tint="@color/text_color"
  12. android:src="@mipmap/ic_search" />

扩展:使用着色相关的属性,tint,tintBackground,tintForground,tintMode,etc.

  1. 使用自定义Shape替代一下简单,规则的图片
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注