你能在一个视图方法上绘制多个位图吗?
Can you draw multiple Bitmaps on a single View Method?
目前我正在尝试制作一些鱼在周围移动的动画。我已经成功添加了一条鱼,并使用 canvas 和 Bitmap 将其设置为动画。但目前我正在尝试添加我在 Photoshop 中制作的背景,每当我将其作为位图添加并将其绘制到 canvas 时,没有显示背景并且鱼开始在屏幕上滞后。我想知道我是否需要制作一个新视图 class 并在不同的 canvas 上绘制,或者我是否可以使用相同的视图?感谢您的帮助!
如果你们有兴趣,这里是代码:
public class Fish extends View {
Bitmap bitmap;
float x, y;
public Fish(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fish1);
x = 0;
y = 0;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, x, y, null);
if (x < canvas.getWidth())
{
x += 7;
}else{
x = 0;
}
invalidate();
}
}
您可以绘制任意多的位图。每个都会覆盖之前的。因此,先画背景,再画其他图像。请确保在您的主要图像中,您在希望背景显示的地方使用透明像素。
在您的代码中,不要调用 Invalidate() - 这就是导致 Android 调用 onDraw() 的原因,并且只应在某些数据已更改并需要重绘时从其他地方调用。
您可以这样做,其中 theView 是包含您的动画的视图:
在您的 activity 中,将此代码放入 onCreate()
myAnimation();
然后
private void myAnimation()
{
int millis = 50; // milliseconds between displaying frames
theView.postDelayed (new Runnable ()
{
@Override public void run()
{
theView.invalidate();
myAnimation(); // you can add a conditional here to stop the animation
}
}, millis);
}
目前我正在尝试制作一些鱼在周围移动的动画。我已经成功添加了一条鱼,并使用 canvas 和 Bitmap 将其设置为动画。但目前我正在尝试添加我在 Photoshop 中制作的背景,每当我将其作为位图添加并将其绘制到 canvas 时,没有显示背景并且鱼开始在屏幕上滞后。我想知道我是否需要制作一个新视图 class 并在不同的 canvas 上绘制,或者我是否可以使用相同的视图?感谢您的帮助! 如果你们有兴趣,这里是代码:
public class Fish extends View {
Bitmap bitmap;
float x, y;
public Fish(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fish1);
x = 0;
y = 0;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, x, y, null);
if (x < canvas.getWidth())
{
x += 7;
}else{
x = 0;
}
invalidate();
}
}
您可以绘制任意多的位图。每个都会覆盖之前的。因此,先画背景,再画其他图像。请确保在您的主要图像中,您在希望背景显示的地方使用透明像素。
在您的代码中,不要调用 Invalidate() - 这就是导致 Android 调用 onDraw() 的原因,并且只应在某些数据已更改并需要重绘时从其他地方调用。
您可以这样做,其中 theView 是包含您的动画的视图:
在您的 activity 中,将此代码放入 onCreate()
myAnimation();
然后
private void myAnimation()
{
int millis = 50; // milliseconds between displaying frames
theView.postDelayed (new Runnable ()
{
@Override public void run()
{
theView.invalidate();
myAnimation(); // you can add a conditional here to stop the animation
}
}, millis);
}