我正在编写一个游戏,现在我正在制作一个在屏幕上上下移动的精灵。在屏幕上绘制精灵之后,我正在尝试绘制一个永久位图来代替动画精灵的位置,有点像一条线索。但是,我不确定如何永久绘制Canvas或将位图保存到画布,以便在onDraw更新时它保留在屏幕上。我希望从屏幕上移动的角色留下一个从位图中绘制出来的路径。有没有办法做到这一点?我正在使用Android SDK(Eclipse)和Windows 7上的Java进行编程。
答案 0 :(得分:0)
我们的想法是独立计算角色及其踪迹:
基本解决方案
Path mCharacterPath=new Path();
public void onDraw(Canvas canvas) {
canvas.drawBitmap (mCharacter, mPosX, mPosY, mCharacterPaint);
canvas.drawPath (mCharacterPath, mPathPaint);
}
public void add_point_to_path(int x, int y) {
mPath.lineTo(x,y);
}
所以每隔一段时间,你只需要打电话
add_point_to_path (mPosX, mPosY);
并将当前精灵位置添加到路径中。
更改mPathPaint,您可以自定义路径类型,您可以猜到。此外,您可以添加弧线,曲线等...
BEtter解决方案
另一个解决方案是在所有内容下创建一个透明的位图:
public void onDraw(Canvas canvas) {
// we draw our auxiliary bitmap that contains all the trails
canvas.drawBitmap (mTransparentBitmapForTrails, 0, 0, mTransparentBitmapPaint);
.
// then we draw the usual stuff, characters, etc...
canvas.drawBitmap (mCharacterBimap, mPosX, mPosY, mCharacterPaint);
.
.
}
// this creates a transparent background the size of the screen
// you will render trails here and they all will be painted at once in onDraw below the craracters
Bitmap mBitmapForTrails;
Canvas mCanvasForTrails;
public void initializeBitmapForTrails() {
mBitmapForTrails=new Bitmap(); // checkout how to create bitmaps with specific w&h, can't remember at the moment.
mCanvasForTrails=new Canvas(mBitmapForTrails); // we create a canvas to draw in that bitmap
}
// this will paint the trail in our secondary bitmap. This secondary bitmap doesn't get
// erased, so the drawTrail()'s are accumulative
public void drawTrail (int x, int y) {
mCanvasForTrails.drawBitmap(your_cool_trail_bitmap, x, y, mTrailPaint);
invalidate(); // this works, but for performance you'll later do invalidate(rect), so Android only repaints the changed portion of the bitmap. That rect will be the rectangle occupied by the trail bitmap. ie. (x,y,x+trailw,y+trialh)
}
因此您将绘制所有路径到该位图。这样做的好处是路径可以非常复杂而不会影响性能。