【问题标题】:Bitmap canvas.drawBitmap method in androidandroid中的位图canvas.drawBitmap方法
【发布时间】:2014-09-28 06:58:42
【问题描述】:

基本上我想用 drawBitmap 方法替换 drawcircle 方法。这个想法是用我导入的图像替换圆圈。

这是我的资源方法

   // Create the bitmap object using BitmapFactory
    // Access the application resource, and then retrieve the drawable
    Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ball); 

我想更改 drawcircle 方法,而是用 drawbitmap 替换它。

// Create a new class extended from the View class
class GameView extends View
{
    Paint paint = new Paint();

    // Constructor
    public GameView(Context context)
    {
        super(context);
        setFocusable(true);
    }

    // Override the onDraw method of the View class to configure
    public void onDraw(Canvas canvas)
    {
        // Configure the paint which will be used to draw the view
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        // If the game is over
        if (isLose)
        {
            paint.setColor(Color.RED);
            paint.setTextSize(40);
            canvas.drawText("Game Over", 50, 200, paint);
        }
        // Otherwise
        else
        {
            // set the color of the ball
            paint.setColor(Color.rgb(240, 240, 80));
            canvas.drawCircle(ballX, ballY, BALL_SIZE, paint);
            // set the color of the racket
            paint.setColor(Color.rgb(80, 80, 200));
            canvas.drawRect(racketX, racketY, racketX + RACKET_WIDTH,
                    racketY + RACKET_HEIGHT, paint);
        }
    }

我知道我必须以某种方式替换 canvas.drawCircle,但到目前为止我所做的每一次尝试都没有奏效。 如果有人可以提供帮助,将不胜感激。

【问题讨论】:

  • 我希望将 canvas.drawCircle 替换为一个看起来像球的图像,而不是只画一个圆圈。

标签: java android eclipse canvas bitmap


【解决方案1】:

更改以下代码:

    // set the color of the ball
    paint.setColor(Color.rgb(240, 240, 80));
    canvas.drawCircle(ballX, ballY, BALL_SIZE, paint);

到:

canvas.drawBitmap(bitmap, null, destRect, null);

在上面的代码中,位图是指您在代码中创建的那个,而 desRect 是一个 Rect,它决定了在哪里绘制该位图。可以这样计算:

  Rect destRect = new Rect(ballX - BALL_SIZE, ballY - BALL_SIZE, ballX + BALL_SIZE, ballY + BALL_SIZE);

记得在onDraw方法之外计算,以防出现效率问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多