在 Android Canvas 上旋转位图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3496036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:28:10  来源:igfitidea点击:

Rotate Bitmap on Android Canvas

android

提问by fredley

I have some objects which I draw onto a Canvas as part of a SurfaceView. I want to be able to rotate these programmatically, e.g. myParticle.setRotation(90);Here's my (simplified) code to draw the Particle at the moment:

我有一些对象作为 SurfaceView 的一部分绘制到 Canvas 上。我希望能够以编程方式旋转这些,例如,myParticle.setRotation(90);这是我目前绘制粒子的(简化)代码:

public class Particle {

  public void draw(Canvas canvas){
    image.setBounds((int)(xPos), (int)(yPos), (int)(xPos+radius), (int)(yPos+radius));
    image.draw(canvas);
  }

}

采纳答案by Romain Guy

You just have to call

你只需要打电话

canvas.rotate(90) :) // 90 is degree.

canvas.rotate(90) :) // 90 is degree.

回答by Bondax

To me it seems cleaner to do this:

对我来说,这样做似乎更干净:

Matrix rotator = new Matrix();

// rotate around (0,0)
rotator.postRotate(90);

// or, rotate around x,y
// NOTE: coords in bitmap-space!
int xRotate = ...
int yRotate = ...
rotator.postRotate(90, xRotate, yRotate);

// to set the position in canvas where the bitmap should be drawn to;
// NOTE: coords in canvas-space!
int xTranslate = ...
int yTranslate = ...
rotator.postTranslate(xTranslate, yTranslate);

canvas.drawBitmap(bitmap, rotator, paint);

This way the canvas stays directed as before, and you can do more stuff with your matrix like translating, scaling etc. and the matrix's content encapsulates the real meaning of your manipulation.

这样画布像以前一样保持定向,你可以用你的矩阵做更多的事情,比如平移、缩放等,矩阵的内容封装了你操作的真正含义。

Edit: Eddie wanted to know around which point the rotation happens.

编辑:埃迪想知道旋转发生在哪个点。

Edit: AndrewOrobator wanted to know how to set the canvas destination coords

编辑:AndrewOrobator 想知道如何设置画布目标坐标