android关于动态壁纸live WallPaper


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;


/**
 * @author Administrator
 * 关于live WallPaper的学习 动态壁纸
 *这个例子的作用就是当滑动屏幕的时候就画一个图片
 *
 *
 *说明:
 *abstract Canvas lockCanvas();锁定画布,一般在锁定后就可以通过其返回的画布对象Canvas,在其上面画图等操作了。
 *
 *abstract Canvas lockCanvas(Rect dirty); 锁定画布的某个区域进行画图等..因为画完图后,会调用下面的unlockCanvasAndPost来改变显示内容。
 * 相对部分内存要求比较高的游戏来说,可以不用重画dirty外的其它区域的像素,可以提高速度。 
*
*abstract void unlockCanvasAndPost(Canvas canvas);结束锁定画图,并提交改变。
 *
 *
 */
public class WallPaper extends WallpaperService
{


@Override
public Engine onCreateEngine()
{
//必须返回一个动态壁纸的引擎,用户绘制图片和相关的逻辑
return new MyEngine();
}


/**
* @author Administrator
*动态壁纸的引擎,用户绘制图片和相关的逻辑
*/
class MyEngine extends Engine
{
//图片的位置
float x = 220;
float y = 220;


//画图的图片
Bitmap bitmap ;

//画笔
Paint paint = new Paint();
//消息传递
Handler handler = new Handler();
//画图线程
Runnable runnable = new Runnable()
{
@Override
public void run()
{
drawFrame();
}
};


@Override
public void onCreate(SurfaceHolder surfaceHolder)
{
//当引擎创建的时候,配置参数
super.onCreate(surfaceHolder);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
paint.setAntiAlias(true);
paint.setStrokeWidth(2);
setTouchEventsEnabled(true);
}


@Override
public void onDestroy()
{
super.onDestroy();
handler.removeCallbacks(runnable);
}


@Override
public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset)
{
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
}


@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
super.onSurfaceChanged(holder, format, width, height);
}


@Override
public void onTouchEvent(MotionEvent event)
{
if( event.getAction() == MotionEvent.ACTION_MOVE )
{
System.out.println("onTouchEvent1");
x = event.getX();
y = event.getY();
drawFrame();
}
System.out.println("onTouchEvent2");
super.onTouchEvent(event);
}


@Override
public void onVisibilityChanged(boolean visible)
{
if(visible  )
{
drawFrame();
}
else
{
handler.removeCallbacks(runnable);
}
}



public void drawFrame()
{
SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try
{
//得到画笔并且枷锁
c = holder.lockCanvas();
if( c != null )
{
c.save();
c.drawColor(0xffffff);
c.drawBitmap(bitmap, x,y, paint);
System.out.println("drawFrame");
c.restore();
}
}
finally
{
if( c != null )
{
holder.unlockCanvasAndPost(c);
}
}
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 1000);
}

}




}

你可能感兴趣的:(android,null,Class,import,float,引擎)