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();
4

1 回答 1

3

在 Android 源代码的 Camera 应用中查看 ImageViewTouchBase;它的“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());
}
于 2010-01-29T17:56:34.590 回答