2015-10-18 86 views
1

我要輪轉圖片經常(多次一秒)和顯示它。爲了準備這個,圖像必須縮放以適合視圖。在Android UI中旋轉和顯示圖像的最有效方法是什麼?

我第一次做的是定義一個Drawable,將它加載到ImageView中並調用setRotation()。但它是因爲API級別11只supportet,而不是9

<ImageView 
    android:id="@+id/image" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:adjustViewBounds="true" 
    android:scaleType="fitCenter" 
    android:src="@drawable/image" /> 

這給出了一個非常糟糕的性能比較(如預期),但什麼是最effcient /合適的方式來做到這一點?圖像包含透明區域,如果這很重要。我應該使用硬件加速嗎?

This答案以某種方式與此主題相關。但在我的情況下,旋轉必須進行多次,而縮放只能進行一次。

在我工作了很長一段時間之後,我被困在這一點,並在此尋求幫助。如果您還有其他問題,請發表評論,我會很樂意回答他們。

+0

這是旋轉的恆定動畫,或者是由用戶手勢控制的旋轉角,或...? –

+0

它由一個傳感器控制,所以它不是**不變**。 @kris –

回答

1

我會假設你的傳感器讀數是模型,在這裏建立了一個偵聽更改傳感器,而不是一個(輪詢)模式。我還會假設回調發生在非UI線程上(如果不是,它應該)。

既然你旋轉圖像我還假設您的源位圖就像是在錶盤針圓形圖像等

  • 創建View子類。我會稱之爲SensorView。你將自己做繪畫,所以你並不需要ImageView
  • 您的傳感器回調將需要對該活動的引用或有一些方法來在UI線程上運行更新。
  • 當您的傳感器發生火災時,獲取讀數並將其設置在視圖上。

    actviity.runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         mSensorView.setReading(val); 
        } 
    }); 
    
  • SensorView將有一個價值的閱讀,一個Bitmap的圖像和Matrix用於將位圖。

    public class SensorView extends View { 
    
        private float mReading; // I use float as an example; use whatever your sensor device supports 
        private Bitmap mBitmap; 
        private Matrix mMatrix; 
        private RectF mBitmapRect; 
        private RectF mViewRect; 
    
        public SensorView(Context context) { 
         this(context, null); 
        } 
    
        public SensorView(Context context, AttributeSet attrs) { 
         super(context, attrs); 
    
         // set up your Bitmap here; don't worry about scaling it yet 
         mBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.sensor_bitmap); 
    
         mMatrix = new Matrix(); 
         mBitmapRect = new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight()); 
         mViewRect = new RectF(); 
        } 
    
        public void setReading(float reading) { 
         mReading = reading; 
         postInvalidate(); // refresh the display 
        } 
    
        @Override 
        public void onDraw(Canvas canvas) { 
    
         mViewRect.right = getWidth(); 
         mViewRect.bottom = getHeight(); 
         mMatrix.reset(); 
    
         // center and scale the image 
         mMatrix.setRectToRect(mBitmapRect, mViewRect, ScaleToFit.CENTER); 
    
         // do the rotation 
         float theta = ... // compute angle based on mReading 
         mMatrix.preRotate(theta, mBitmapRect.centerX(), mBitmapRect.centerY()); 
    
         // draw the bitmap with the matrix 
         canvas.drawBitmap(mBitmap, mMatrix, null); 
        } 
    } 
    

[位測試之後編輯]

+0

好的,謝謝!這似乎比我的「解決方案」更直截了當,並帶走了處理程序。我會盡快測試! –

+0

如果遇到問題,請告訴我。我會自己測試它。 –

+0

hey @felixd,我有一個小錯字('Content'),我對非UI線程錯了,'setReading()'必須在UI線程上運行。看到我更新的答案。如果您在運行時遇到任何問題,請使用您的所有新代碼更新您的問題,然後查看它。 –

相關問題