android:Canvas繪製自旋轉Bitmap

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.