如何将位图从一个坐标移动到另一个坐标-Android开发



我想沿着SurfaceView中的连续坐标移动位图图像。我在SurfaceView上的坐标(x1, y1)中绘制了位图myBall,如下所示(部分代码)(

public class MainSurfaceView extends SurfaceView implements Runnable {...
...
@Override
public void run() {
while (isRunning) {
if (!myHolder.getSurface().isValid())
continue; 
Canvas canvas;// Define canvas to paint on it
canvas = myHolder.lockCanvas();
//Draw full screen rectangle to hold the floor map.
Rect dest = new Rect(0, 0, getWidth(), getHeight());
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawBitmap(bgImage, null, dest, paint);
//This is the ball I want to move
canvas.drawBitmap(myBall, x1, y1, null);
myHolder.unlockCanvasAndPost(canvas);
}
}

现在我想把它移到(x2, y2),然后是(x3, y3)。。。需要多少就有多少,一个接一个。我试过使用TranslateAnimation,但做不到。

我已经学会了如何使用坐标制作动画。我将解释我跳了什么,这将对其他人有所帮助:首先,我将坐标保存为点对象

List<Point> point_list = new ArrayList<Point>();
point_list.add(new Point(x_value, y_value));//Add the x and y coordinates to the Point

保留实现Runnable并使用onDraw()方法而不是run()方法,如下所示:

public class MainSurfaceView extends SurfaceView {...
.... 
@Override
protected void onDraw(Canvas canvas) {
// Draw full screen rectangle to hold the floor map.
Rect fArea = new Rect(0, 0, getWidth(), getHeight());
Paint paint = new Paint();
paint.setFilterBitmap(true);
// draw the paint on the rectangle with the floor map
canvas.drawBitmap(bgImage, null, fArea, paint);
// Get the coordinates of x & y as Point object
List<Point> myPoints = point_list;
// Start printing myBall on the floor (view)
try {
if (index < myPoints.size()) {
// Increment the value of index and use it as index for the point_list
index++;
}
// Print myBall in each coordinates of x & y using the index 
canvas.drawBitmap(myBall, myPoints.get(index).x, myPoints.get(index).y, null);
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
}

我使用try-and-catch来避免IndexOutOfBoundryExeption干杯

我想这可能就是你想要的。你想做的是在位图之间切换,有几种方法可以做到这一点。还有ViewPropertyAnimator,它可以为整个视图设置动画。

最新更新