简体   繁体   English

如何在Android中缩放画布

[英]How To Scale Canvas In Android

I am writing a android game using Canvas as the way to draw everything, the problem is that when i run it on different android phones the canvas dosn't change size i tried using canvas.scale() but that didn't make ai difference. 我正在使用Canvas作为绘制所有内容的方式来编写android游戏,问题是当我在其他android手机上运行它时,canvas不会改变大小,我尝试使用canvas.scale()进行了尝试,但这并没有使AI有所不同。 The code i use for drawing is ... 我用于绘图的代码是...

public void draw( Canvas c, int score )
{   
    Obstical2[] obstmp = Queue.toArray(this.o);
    Coin[] cointmp = QueueC.toArray(this.c);

    for( int i = 0; i < obstmp.length; i++ )
    {
        obstmp[i].draw(c);
    }

    for( int i = 0; i < cointmp.length; i++ )
    {
        cointmp[i].draw(c);
    }
    c.drawText(String.format("%d", score ), 20, 50, textPaint);

    if( isWon && isStarted ) c.drawText("YOU WON", 20, 400, resPaint);
    else if( isLost && isStarted ) c.drawText("YOU LOST", 20, 400, resPaint);
}

The function above calls the draw functions for the entity's on the screen, theses function are as follows 上面的函数调用实体在屏幕上的绘制函数,这些函数如下

Draw Function For Obstical : Obstical的绘制函数:

public void draw( Canvas c )
{
    Log.i("D", "COIN");
    coin.draw(c);
}

Draw Function For Coin : 硬币绘制功能:

public void draw( Canvas c )
{
    obstical.draw(c);
}

How could i make the canvas re-size to it would look the same on any screen ? 我如何才能将画布调整为在任何屏幕上看起来都一样的大小?

Cheers Daniel 干杯丹尼尔

override onMeasure() function and there calculate screen width and screen height and then calculate the scale. 覆盖onMeasure()函数,然后计算屏幕宽度和屏幕高度,然后计算比例。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        screen_width = MeasureSpec.getSize(widthMeasureSpec);
        screen_height= MeasureSpec.getSize(heightMeasureSpec);
}

try this , This gives u the changed screen size 试试这个,这给你改变的屏幕尺寸

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    // TODO Auto-generated method stub
      super.onSizeChanged(w, h, oldw, oldh);
      screen_width = w;
      screen_height= h;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM