2015-10-18 87 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线程上运行。看到我更新的答案。如果您在运行时遇到任何问题,请使用您的所有新代码更新您的问题,然后查看它。 –

相关问题