一、设置墙纸滤镜效果
Demo源码:
public class SetWallpaperActivity extends Activity {
final static private int[] mColors =
{Color.BLUE, Color.GREEN, Color.RED, Color.LTGRAY, Color.MAGENTA, Color.CYAN,
Color.YELLOW, Color.WHITE};
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See res/layout/wallpaper_2.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.wallpaper_2);
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
final Drawable wallpaperDrawable = wallpaperManager.getDrawable();
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setDrawingCacheEnabled(true);
imageView.setImageDrawable(wallpaperDrawable);
Button randomize = (Button) findViewById(R.id.randomize);
randomize.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
int mColor = (int) Math.floor(Math.random() * mColors.length);
//添加滤镜效果
wallpaperDrawable.setColorFilter(mColors[mColor], PorterDuff.Mode.MULTIPLY);
imageView.setImageDrawable(wallpaperDrawable);
//刷新界面
imageView.invalidate();
}
});
Button setWallpaper = (Button) findViewById(R.id.setwallpaper);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try {
//设置墙纸
wallpaperManager.setBitmap(imageView.getDrawingCache());
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
关于 PorterDuff.Mode :http://blog.csdn.net/q445697127/article/details/7867529
关于setDrawingCacheEnabled
View组件显示的内容可以通过cache机制保存为bitmap, 使用到的api有
void setDrawingCacheEnabled(boolean flag),
Bitmap getDrawingCache(boolean autoScale),
void buildDrawingCache(boolean autoScale),
void destroyDrawingCache()
我们要获取它的cache先要通过setDrawingCacheEnable方法把cache开启,然后再调用getDrawingCache方法就可 以获得view的cache图片了。buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果 cache没有建立,系统会自动调用buildDrawingCache方法生成cache。若果要更新cache, 必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。
当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。
ViewGroup在绘制子view时,而外提供了两个方法
void setChildrenDrawingCacheEnabled(boolean enabled)
setChildrenDrawnWithCacheEnabled(boolean enabled)
setChildrenDrawingCacheEnabled方法可以使viewgroup里所有的子view开启cache, setChildrenDrawnWithCacheEnabled使在绘制子view时,若该子view开启了cache, 则使用它的cache进行绘制,从而节省绘制时间。
获取cache通常会占用一定的内存,所以通常不需要的时候有必要对其进行清理,通过destroyDrawingCache或setDrawingCacheEnabled(false)实现。