65.9K
CodeProject 正在变化。 阅读更多。
Home

旋转位图

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2013年8月27日

CPOL
viewsIcon

22110

downloadIcon

613

旋转位图

引言

今天,我将指导一段代码片段,通过使用 Canvas 来旋转原始位图,从而创建一个新的位图。

此外,如果您想裁剪位图,请参考 这个技巧。如果您想将多个位图合并为一个,请参考 这个技巧

Using the Code

要使用画布旋转位图,请关注以下函数

public void drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint) 

旋转的关键点是 matrix,使用方法是

matrix.postRotate(angle, x, y);  
  • angle:将旋转的角度
  • x,y旋转的锚点坐标

根据以上解释,要以中心点作为锚点旋转位图,锚点将是 (bitmap.width/2, bitmap.height/2)

private Bitmap rotateBitmap(float angle) {
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
        R.drawable.original);
    Bitmap rotateBitmap = Bitmap.createBitmap(bitmap.getWidth(),
        bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(rotateBitmap);
    Matrix matrix = new Matrix();
    matrix.postRotate(angle, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
    canvas.drawBitmap(bitmap, matrix, null);
    return rotateBitmap;
}  

而以(左,顶)作为锚点旋转位图,锚点将是(0, 0)

private Bitmap rotate(Bitmap bitmap, float angle) {
    Bitmap rotateBitmap = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(rotateBitmap);
    Matrix matrix = new Matrix();
    matrix.postRotate(angle, 0, 0);
    canvas.drawBitmap(bitmap, matrix, new Paint());
    return rotateBitmap;
}

历史

  • 2013-08-27:创建
  • 2013-08-27:更新,更清晰地说明了锚点,根据用户的评论
  • 2013-08-28:更改了下载源代码的链接名称
© . All rights reserved.