在Android TouchImageView中自动滚动到左上角



我在我的应用程序中使用TouchImageView,其中的图像大于屏幕尺寸。当我启动包含我的TouchImageView的活动时,它当前会自动在屏幕中间显示我的图像中心。我必须手动(使用拖动手势)使左上角可见。但是,我希望默认情况下,图像的左上角在屏幕的左上角可见。

我尝试了imgView.setScrollPosition(0,0),但没有任何结果。我还尝试将比例类型设置为"矩阵",但这会缩小图像,而我希望图像以其原始大小显示。TouchImageView 不支持 fitStart 和 fitEnd 比例类型。

如何滚动到我的触摸图像视图的左上角?

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.frankd.wttv.TouchImageView
        android:id="@+id/imageView"
        android:layout_width = "wrap_content"
        android:layout_height ="wrap_content"
        android:scaleType="matrix"/>
</LinearLayout>

这是我打开布局和设置图像的方法。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myLayout);
    //set timetable image
    TouchImageView imgView = (TouchImageView)findViewById(R.id.imageView);
    imgView.setImageResource(R.drawable.myImage);
    //TODO: scroll to top left corner of image
}

问题的原因是 TouchImageView 中的 scrollToPosition(x,y) 不使用 x 和 y 像素作为输入,而是使用 0 到 1 之间的数字来反映图像大小的一部分。

此外,scrollToPosition(x,y) 在 TouchImageView 的中心设置图像的一个点。因此,如果您在 TouchImageView 上调用 scrollToPosition(0.5,0.5),图像的中心将显示在 TouchImageView 的中心。我们需要计算图像的哪个点需要放置在TouchImageView的中心,以使其很好地对齐。

我在 TouchImageView.java

中创建了函数 scrollToTopLeft(),它只有在 onMeasure() 结束时从 TouchImageView.java 文件中调用它时才有效。如果你早点调用它,getWidth() 和 getHeight() 将返回 0,因为视图还没有被调整大小。

public void scrollToTopLeft() {
    try {
        float x, y, viewWidth, viewHeight, viewCenterX, viewCenterY, imageWidth, imageHeight;
        //these calls will only work if called after (or at the end of) onMeasure()
        viewWidth = this.getWidth();
        viewHeight = this.getHeight();
        // get center of view
        viewCenterX = viewWidth / 2;
        viewCenterY = viewHeight / 2;
        // get image height and width
        imageWidth = getImageWidth();
        imageHeight = getImageHeight();
        //calculate the x and y pixels that need to be displayed in at the center of the view
        x = viewWidth / imageWidth * viewCenterX;
        y = viewHeight / imageHeight * viewCenterY;
        //calculate the value of the x and y pixels relative to the image
        x = x / imageWidth;
        y = y / imageHeight;
        setScrollPosition(x, y);
    } catch (Exception E) {
        Log.v(TAG, E.toString());
    }
}

最新更新