java - 如何调整 Canvas 中位图的大小?

标签 java android canvas bitmap

我在此处和 Google 上找不到其他问题的答案。

问题是,在 GameView 中创建的位图在某些屏幕上太大(在我的 Galaxy S5 上它们是正确的),应该使用 GameView.getDensity() 进行缩放。

GameView类:

bmp = BitmapFactory.decodeResource(getResources(), R.drawable.circle_green);

圆类:

private int score;
private int y = 0;
private int x = 0;
private int Speed, width, height;
private GameView theGameView;
private Bitmap bmp;
private Random rnd;

public Circle(GameView theGameView, Bitmap bmp) {
    this.theGameView = theGameView;
    this.bmp = bmp;
    this.width = bmp.getWidth();
    this.height = bmp.getHeight();
    this.score = theGameView.getScore();

    rnd = new Random();
    x = (int) (30 * theGameView.getDensity() + rnd.nextInt((int) (theGameView.getWidth() - width - 50 * theGameView.getDensity())));
    y = (int) (60 * theGameView.getDensity() + rnd.nextInt((int) (theGameView.getHeight() - height - 80 * theGameView.getDensity())));
    Speed = (int) (2 * theGameView.getDensity());
}

private void bounceOff() {
    if (x + 10 * theGameView.getDensity() > theGameView.getWidth() - width - Speed || x + Speed < 10 * theGameView.getDensity()) {
        Speed = -Speed;
    }

    x = x + Speed;

    if (y + 60 * theGameView.getDensity() > theGameView.getHeight() - height - Speed || y + Speed < 60 * theGameView.getDensity()) {
        Speed = -Speed;
    }

    y = y + Speed;
}

public void onDraw(Canvas canvas) {
    bounceOff();
    if(canvas != null) {
        canvas.drawBitmap(bmp, x, y, null);
    }
}

public boolean isTouched(float x2, float y2) {
    return x2 > x && x2 < x + width && y2 > y && y2 < y + height;
}

最佳答案

这很容易。只需使用 canvas.scale

    canvas.save();               // Save current canvas params (not only scale)
    canvas.scale(scaleX, scaleY);
    canvas.restore();            // Restore current canvas params

scale = 1.0f将绘制相同可见尺寸的位图

关于java - 如何调整 Canvas 中位图的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35324552/

相关文章:

android - FLASH_MODE_TORCH 和 FLASH_MODE_ON 有什么区别

javascript - 函数中声明的全局对象不能被其他函数访问

javascript - 在 Canvas 上绘制图像 - 比实际大

javascript - 在 Javascript 中在特定时间绘制正方形并然后移动

java - Fragment中TextView的空对象引用

java - 从 IntelliJ 执行文件 IO 时,Spring Boot 会自动重新启动

android - 创建 fragment 时未设置私有(private)字段

java - Firebase Cloud Firestore : Invalid collection reference. 集合引用必须有奇数个段

java - LocalTime 检查时间是否在两个时间之间的范围内的替代方法

java - 在 VS Code 中向 Java 库代码添加断点