2010-01-29 63 views
4

我正在为android编写一个应用程序(尽管我认为这是一个普通问题),我需要显示一个可以滚动和缩放的大图像(在ImageView中)。我设法通过捕获触摸事件和执行矩阵转换来实现滚动工作,并且我正在进行缩放。图像缩放的正确转换

如果我只是对图像应用比例变换,它会放大原点,即屏幕的左上角。我想放大屏幕的中心。 从我读过的,这意味着我需要一个转换,使原点为屏幕的中心。我认为,所需要的是类似以下各项假设屏幕的中心是(5,5)为简单起见...

-Translate by (-5, -5)
-Scale by the zoom factor
-Translate by (+5, +5)*zoomfactor

不幸的是,这似乎没有工作 - 变焦似乎走任何地方,但中心......有人可以帮我在这里?

编辑:这是现在工作

Matrix zoommatrix = new Matrix(); 
    float[] centerpoint = {targetimageview.getWidth()/2.0f, targetimageview.getHeight()/2.0f}; 

    zoommatrix.postScale(zoomfactor, zoomfactor, centerpoint[0], centerpoint[1]); 
    zoommatrix.preConcat(targetimageview.getImageMatrix()); 

    targetimageview.setImageMatrix(zoommatrix); 
    targetimageview.invalidate(); 
+0

你可以发表你的转换代码? – AGrunewald 2010-01-29 16:32:50

回答

3

检查ImageViewTouchBase在Android源代码的相机应用的代码;其“zoomTo”的方法做到这一点:

protected void zoomTo(float scale, float centerX, float centerY) { 
    if (scale > mMaxZoom) { 
     scale = mMaxZoom; 
    } 

    float oldScale = getScale(); 
    float deltaScale = scale/oldScale; 

    mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY); 
    setImageMatrix(getImageViewMatrix()); 
    center(true, true); 
} 

该中心的方法是可能是你真正关心的一点:

protected void center(boolean horizontal, boolean vertical) { 
    if (mBitmapDisplayed.getBitmap() == null) { 
     return; 
    } 

    Matrix m = getImageViewMatrix(); 

    RectF rect = new RectF(0, 0, 
      mBitmapDisplayed.getBitmap().getWidth(), 
      mBitmapDisplayed.getBitmap().getHeight()); 

    m.mapRect(rect); 

    float height = rect.height(); 
    float width = rect.width(); 

    float deltaX = 0, deltaY = 0; 

    if (vertical) { 
     int viewHeight = getHeight(); 
     if (height < viewHeight) { 
      deltaY = (viewHeight - height)/2 - rect.top; 
     } else if (rect.top > 0) { 
      deltaY = -rect.top; 
     } else if (rect.bottom < viewHeight) { 
      deltaY = getHeight() - rect.bottom; 
     } 
    } 

    if (horizontal) { 
     int viewWidth = getWidth(); 
     if (width < viewWidth) { 
      deltaX = (viewWidth - width)/2 - rect.left; 
     } else if (rect.left > 0) { 
      deltaX = -rect.left; 
     } else if (rect.right < viewWidth) { 
      deltaX = viewWidth - rect.right; 
     } 
    } 

    postTranslate(deltaX, deltaY); 
    setImageMatrix(getImageViewMatrix()); 
} 
+0

优秀!我需要的是postScale()的重载以及一个磅秤。现在的缩放代码看起来像这样... 好吧,它不适合,我会编辑我的问题,包括它。所需要的只是将当前变换矩阵乘以四个参数形式的scale()生成的矩阵() – 2010-01-30 01:07:17