標籤:android 旋轉 bitmap matrix 位置
- 需求
在SurfaceView或者普通View中,我們在每個繪製周期(onDraw)中,不僅需要更新繪製Bitmap對象在View中得位置,而且還希望Bitmap能夠以它自身的中心點為圓心,進行自旋轉。
- 解決
使用Canvas的drawBitmap(Bitmap bitmap,Matrix matrix,Paint paint)方法,最重要的就是定製Matrix。
代碼如下:
/** * 繪製自旋轉位元影像 * * @param canvas * @param paint * @param bitmap * 位元影像對象 * @param rotation * 旋轉度數 * @param posX * 在canvas的位置座標 * @param posY */ private void drawRotateBitmap(Canvas canvas, Paint paint, Bitmap bitmap, float rotation, float posX, float posY) { Matrix matrix = new Matrix(); int offsetX = bitmap.getWidth() / 2; int offsetY = bitmap.getHeight() / 2; matrix.postTranslate(-offsetX, -offsetY); matrix.postRotate(rotation); matrix.postTranslate(posX + offsetX, posY + offsetY); canvas.drawBitmap(bitmap, matrix, paint); }
首先,我們將bitmap向左上方移動一半(xy各一半),然後旋轉需要的度數。最後再將center移動回來。然後再移動到位置座標(posX,posY)上。注意,座標(posX,posY)是位元影像的左上方的點。
另外,為了使旋轉連貫,調用該方法時:
rotation += 0.1f * (new Random().nextInt(20));drawRotateBitmap(canvas, paint, bitmap, rotation, posX, posY);
Android開發聯盟QQ群:272209595
android:Canvas繪製自旋轉Bitmap