旋转位图不旋转

时间:2012-08-28 22:07:17

标签: android canvas matrix bitmap

我已经尝试了几个小时来旋转位图但没有成功。我在这个网站上看过很多关于这个主题的文章,似乎首选的解决方案是创建一个临时画布。好吧,我做了这个,我仍然没有看到一个roated位图。

我的位图是一个40x40的蓝色方块,我试图将其旋转45度。那不是要求太多了吗?代码运行时,屏幕上显示的位图是未旋转的原件。 (我也试过翻译也没有成功)

这是我的代码:

// Load the bitmap resource
   fillBMP2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.test1);
   // Copy to a mutable bitmap
   mb = fillBMP2.copy(Bitmap.Config.ARGB_8888, true);
   // Create canvas to draw to
   Canvas offscreenCanvas = new Canvas (mb);
   // Create Matrix so I can rotate it 
   Matrix matrix = new Matrix();
   matrix.setRotate (45); 
   offscreenCanvas.setMatrix (matrix);
   // Send the contents of the canvas into a bitmap
   offscreenCanvas.setBitmap(mb);

稍后在OnDraw中我会执行以下操作:

canvas.drawBitmap(mb, 200, 200, null);

任何想法我做错了什么?好像它应该工作。

由于

3 个答案:

答案 0 :(得分:1)

尝试使用此

Matrix matrix = new Matrix();
matrix.setRotate(15);
canvas.drawBitmap(bmp, matrix, paint);

setRotation 方法接受浮点表示 旋转度。

答案 1 :(得分:1)

试试这个......

    Matrix matrix = new Matrix();

    float px = 200;

    float py = 200;

    matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getWidth()/2);

    matrix.postRotate(45);

    matrix.postTranslate(px, py);

    canvas.drawBitmap(bitmap, matrix, paint);

答案 2 :(得分:0)

您肯定想要使用转换:请查看此link

基本上是这样的:

// save the canvas
ctx.save();

// move origin to center
ctx.translate(x,y); 

// rotate
ctx.rotate(angle * (Math.PI / 180));

// draw image
ctx.drawImage(image, x, y, w, h, .w/2, h/2, w, h);

// restore
ctx.restore();