package com.kerwin.livewallpaper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.view.SurfaceHolder;
public class LiveWallpaperService extends WallpaperService {
private int width,height,xPixelOffset;
private Bitmap bg;
protected float bgOffsetStep;
private boolean visible;
private Engine eigine;
private final Handler HANDLER = new Handler();
private final Runnable DRAWTHREAD = new Runnable(){
@Override
public void run(){
LiveWallpaperService.this.draw();
}
};
private synchronized void draw(){
SurfaceHolder holder = this.eigine.getSurfaceHolder();
Canvas canvas = holder.lockCanvas(null);
if(canvas != null){
if(Float.isNaN(bgOffsetStep)){
canvas.drawBitmap(bg, null, new Rect(-this.bg.getWidth() / 3,0,this.bg.getWidth()+width-this.bg.getWidth() / 3,this.height), null);
}else{
canvas.drawBitmap(bg, null, new Rect(xPixelOffset,0,(int)(this.bg.getWidth()+width+xPixelOffset*bgOffsetStep),this.height), null);
}
holder.unlockCanvasAndPost(canvas);
}
if(this.visible){
this.HANDLER.post(DRAWTHREAD);
}
}
private void stop(){
this.HANDLER.removeCallbacks(DRAWTHREAD);
}
private void loadBitmap(){
this.bg = BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.wallpaper));
}
@Override
public Engine onCreateEngine() {
return eigine = new MyEngine();
}
class MyEngine extends Engine{
public MyEngine(){
super();
loadBitmap();
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height){
super.onSurfaceChanged(holder, format, width, height);
LiveWallpaperService.this.width = width;
LiveWallpaperService.this.height = height;
}
@Override
public void onVisibilityChanged(boolean visible){
super.onVisibilityChanged(visible);
LiveWallpaperService.this.visible = visible;
if(visible){
LiveWallpaperService.this.draw();
}else{
LiveWallpaperService.this.stop();
}
}
@Override
public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset){
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
LiveWallpaperService.this.xPixelOffset = xPixelOffset;
LiveWallpaperService.this.bgOffsetStep = ((float)(bg.getWidth()/Math.ceil((width/(width*xOffsetStep))+1))/(float)width)/xOffsetStep;
}
}
}