Android Live wallpaper - onOffsetsChanged
Is there a better way to move the bitmap inside a canvas without redrawingBitmap every time, for every single one?
public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels) {
final SurfaceHolder holder = getSurfaceHolder()开发者_Go百科;
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
c.drawBitmap(this.ImageI, xPixels, 0, null);
c.drawBitmap(this.ImageII, xPixels, 0, paint);
}
} finally {
if (c != null) holder.unlockCanvasAndPost(c);
}
}
You are asking: is there a better way? The answer is: no. You need to redraw your whole scene, background and all, every frame. Also, generally speaking, you don't want to draw in onOffsetsChanged; just update variables that you're using in your runnable. Take a look at how the Cube example in the SDK works. Joey's example is correct, too. Hope this helps
You can do like I usually do in a situation where you are reading and modifying a location or image via the offsets changing. I use onOffsetsChanged to feed information to a constant variable that is updated in my draw routine automatically as it changes.
Start by defining the constants you want to work with like so...
Private float mXOffset = 0,
mYOffset = 0,
mXStep = 0,
mYStep = 0,
mXPixels = 0,
mYPixels = 0;
In this example I am capturing all of the values from the onOffsetsChanged event, you need only define and capture the offsets, steps, or pixels you will be using.
public void onOffsetsChanged(float xOffset, float yOffset, float xStep, float yStep, int xPixels, int yPixels) {
mXOffset = xOffset;
mYOffset = yOffset;
mXStep = xStep;
mYStep = yStep;
mXPixels = xPixels;
mYPixels = yPixels;
DrawStuff();
}
Once you have this data it will give you a little more power and flexibility to use in your application. You can call your canvas updates now like the following and when the offsets change each time your draw routine is called you can use these numbers to modify location of image, speed of movement, or any other mathematical calculation you would like.
private void DrawStuff(){
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
c.drawBitmap(this.ImageI, mXPixels,mYPixels + mYOffset,null);
c.drawBitmap(this.ImageII, xPixels, 0, paint);
}
} finally {
if (c != null) holder.unlockCanvasAndPost(c);
}
}
and so on and so forth. Hope this is what you was asking I wasn't entirely clear. This will also give you the ability to use these offsets, steps, and locations elsewhere if you have a need.
精彩评论