ApiDemos setWallpaper

代码范例中用到的类:

 

1. android.app.WallpaperManager 

 

Provides access to the system wallpaper. With WallpaperManager, you can get the current wallpaper, get the desired dimensions for the wallpaper, set the wallpaper, and more. Get an instance of WallpaperManager with getInstance().

 

是管理wallpaper的主要类,通过它我们可获取当前系统壁纸、设置壁纸等等。

 

常用方法:

 

static WallpaperManager  getInstance(Context context):

获取指定上下文的WallpaperManager实例。

 

Drawable getDrawable():

获取当前系统的墙纸,如果系统没有设置墙纸,会返回系统默认的墙纸。

 

void setBitmap(Bitmap bitmap):使用bitmap更换当前系统的墙纸。

 

void setResource(int resid):使用res中注册的图片资源更换当前系统的墙纸。

 

2.android.graphics.drawable.Drawable :

 

A Drawable is a general abstraction for "something that can be drawn." Most often you will deal with Drawable as the type of resource retrieved for drawing things to the screen; the Drawable class provides a generic API for dealing with an underlying visual resource that may take a variety of forms. Unlike a View, a Drawable does not have any facility to receive events or otherwise interact with the user.

Though usually not visible to the application, Drawables may take a variety of forms:

  • Bitmap: the simplest Drawable, a PNG or JPEG image.一般用于处理jpg和png图
  • Nine Patch: an extension to the PNG format allows it to specify information about how to stretch it and place things inside of it.
  • Shape: contains simple drawing commands instead of a raw bitmap, allowing it to resize better in some cases.
  • Layers: a compound drawable, which draws multiple underlying drawables on top of each other.  用于图层方式存取多个Drawable,可以用getDrawable(int index)取得其中一个Drawable,对应setLayer(int);
  • States: a compound drawable that selects one of a set of drawables based on its state.               为不同的状态存取不同的Drawable,通过指定状态的id值,可以取得如获得焦点,失去焦点等时的不同图像             如:addState( new int[]{R.attr.state_focused, R.attr.state_pressed}, ... ); 对应setState(int[]);
  • Levels: a compound drawable that selects one of a set of drawables based on its level.                可以指定在不同的级别中显示不同的图,如:addLevel(1, 3, ...); // 在第1到3级的时候显示相应的图,对应setLevel(int)
  • Scale: a compound drawable with a single child drawable, whose overall size is modified based on the current level.  ScaleDrawable(Drawable drawable, int gravity, float scaleWidth, float scaleHeight)// 这是一个可以缩放的drawable,可以将图缩放到指定的大小

 

Drawable就是一个可画的对象,其可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable),还有可能是一个图层(LayerDrawable),我们根据画图的需求,创建相应的可画对象,就可以将这个可画对象当作一块“画布(Canvas)”,在其上面操作可画对象,并最终将这种可画对象显示在画布上,有点类似于“内存画布“。

 

 

   Drawable d = this.getResources().getDrawable(R.drawable.a1);

   this指代Activity, R.drawable.a1是在\res\drawable文件夹中的名称为a1的图。

 

 

例:

Drawable[] array = new Drawable[] {

this.getResources().getDrawable(R.drawable.a1),

this.getResources().getDrawable(R.drawable.a2),

this.getResources().getDrawable(R.drawable.a3),

this.getResources().getDrawable(R.drawable.a4)

};

LayerDrawable ld = new LayerDrawable( array );

 

ImageButton imgBtn = new ImageButton( this );

imgBtn.setImageDrawable( ld.getDrawable(2) );

// 显示a3这个图

 

 

/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.app;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

import java.io.IOException;

import android.app.Activity;
import android.app.WallpaperManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * <h3>SetWallpaper Activity</h3>
 *
 * <p>This demonstrates the how to write an activity that gets the current system wallpaper,
 * modifies it and sets the modified bitmap as system wallpaper.</p>
 */
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.
     */
    @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);//只有设置为true才能读写ImageView对象的图片信息
        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();
                }
            }
        });
    }
}

 最后 ,不要忘了在清单中添加许可:

 

 <uses-permission android:name="android.permission.SET_WALLPAPER" />
 

 

你可能感兴趣的:(demo)