从画布上的单个位图绘制多次 [英] Draw multiple times from a single bitmap on a canvas

查看:114
本文介绍了从画布上的单个位图绘制多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有以下位图: 位图云; cloud = BitmapFactory.decodeResource(getResources(),R.drawable.cloud);

Basically I have the following bitmap: Bitmap cloud; cloud = BitmapFactory.decodeResource(getResources(), R.drawable.cloud);

我想做的是在画布上的不同(随机)位置多次绘制相同的位图(在本例中为云).我想在视图的OnDraw方法中执行此操作.

What I want to do is draw the same bitmap(in this case cloud) multiple times in different(random) locations on canvas. I want to do this in the OnDraw method of my view.

因此最终产品应如下所示:

So the final product should look like this:

但是

这是用于在同一画布上多次绘制位图的代码:

This is the code for drawing the bitmap multiple times on the same canvas:

protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

    // canvas.drawColor(Color.BLUE);
    //drawBackground(canvas);

    //objectMovement(canvas);

    for (int i = 0; i < 500; i += 50) {
        canvas.drawBitmap(cloud, 50 + rand.nextInt(350),
                10 + rand.nextInt(350), null);
    }

    invalidate();
}

如您所见,我正在使用random生成位图的位置,并且每次在画布上的不同位置绘制位图时.

As you can see, I'm using random to generate the position of the bitmap, and every time the bitmap is drawn in a different place on the canvas.

唯一的问题是,每次调用invalidate()时,for循环中的绘制都会再次发生.因此,图纸(云)到处都在快速移动.

The only problem is, every time invalidate() is being called, the drawing in the for loop happens again. Because of this, it looks like the drawings(cloud) is moving very fast all over the place.

搜索了一段时间后,我发现了这个问题: 从单个位图绘制多次

After searching for a while, I found this question: Draw multiple times from a single bitmap

与我的问题几乎相同,但是很遗憾,那里没有正确的答案.

It's pretty much the same question as my question, but unfortunately, there is no right answer there.

那我该如何实现呢?

谢谢!

推荐答案

第一个问题是每帧读取位图10次,这是完全不必要的.实例化类时,应一次读入位图.我还添加了一个画图.我不知道这是否完全必要,只是万一您决定在自己的绘制方法中做更多的事情.

The first problem is that you are reading in the bitmap 10 times per frame which is completely unnecessary. You should read the bitmap in once when you instantiate your class. I've also added a Paint. I don't know if it's completely necessary but just incase you decide to do more in your draw method it's there.

public class MyView extends View
{
    private Bitmap _cloud;
    private Paint _paint;

    public MyView(Context context)
    {
        super(context);
        _cloud = BitmapFactory.decodeResource(getResources(),R.drawable.cloud);
        _paint = new Paint();
    }

    protected void onDraw(Canvas canvas) 
    {
        for(int i = 0; i < 500; i += 50) 
        {
            canvas.drawBitmap(_cloud, 50 + rand.nextInt(350rand.nextInt(350)), 10 + i, _paint);
        }
    }
}

这篇关于从画布上的单个位图绘制多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆