Android 利用矩阵旋转位图后的缩放比例和保持比例

Android 利用矩阵旋转位图后的缩放比例和保持比例,android,matrix,rotation,scale,Android,Matrix,Rotation,Scale,我有一张太阳的照片,860x860像素。 我想旋转太阳,固定点是屏幕的中心。 到目前为止,我得到的是: class GraphicalMenu extends View{ int screenH; int screenW; int angle; Bitmap sun, monster; public GraphicalMenu(Context context){ super(context); BitmapFactor

我有一张太阳的照片,860x860像素。 我想旋转太阳,固定点是屏幕的中心。 到目前为止,我得到的是:

class GraphicalMenu extends View{

    int screenH;
    int screenW;
    int angle;
    Bitmap sun, monster;

    public GraphicalMenu(Context context){
        super(context);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        sun = BitmapFactory.decodeResource(getResources(),R.drawable.sun,options);
        monster = BitmapFactory.decodeResource(getResources(),R.drawable.monster,options);
    }

    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        screenH = h;
        screenW = w;
        sun = Bitmap.createScaledBitmap(sun, w, h, true);
        monster = Bitmap.createScaledBitmap(monster, w, h, true);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

      //Increase rotating angle.
        if (angle++ >360)
            angle =0;

        Matrix matrix = new Matrix();
        matrix.setRotate(angle , getWidth()/2, getHeight()/2);
        canvas.drawBitmap(sun, matrix, new Paint());

        //Call the next frame.
        canvas.drawBitmap(monster,0 , 0, null);

        invalidate();
    }
}
我试图改变这一行:

sun = Bitmap.createScaledBitmap(sun, w, h, true);
致:

但随后太阳离开屏幕中心,向右旋转很远。 我怎样才能使太阳适合屏幕? 我怎样才能让它保持它的比例呢

编辑 在我的N5上运行它的屏幕截图和太阳图片。


如果我理解正确,您的代码有几个问题:

  • 如果要多次调用onSizeChanged(),则需要保留原始位图(预缩放),否则当再次放大位图时,它们将看起来是像素化的,因为每次缩小它们时,都会丢失信息
  • 当您提供一个矩阵来转换位图以便在画布上绘制时,该矩阵将应用于位图本身,而不是整个屏幕。因此,在进行drawBitmap()调用时,实际请求的是位图围绕本地点(getWidth()/2,getHeight()/2)旋转,而不是围绕屏幕点旋转
  • 实际上,你不是围绕屏幕中心旋转,而是围绕视图的中心旋转。除非视图占据整个屏幕,否则无法获得预期效果
    我无法准确指出您的问题所在,但上传一些图像可能会澄清您试图实现的目标以及您当前的状况。

    我将画布设置为:GraphicalMenu gm=new GraphicalMenu(此);setContentView(gm);所以它覆盖了整个屏幕。所以宽度和高度应该是正确的。我还更新了图片,希望能更容易理解我想要实现的目标。:)
    sun = Bitmap.createScaledBitmap(sun, h, h, true);