Android: прокрутка изображения - PullRequest
23 голосов
/ 17 июня 2010

У меня есть ImageView, которое в два раза больше нормального экрана (960 провалов). Я хотел бы прокрутить его вверх и вниз на экране. В нижней части экрана должна быть кнопка. Я пробовал различные комбинации ScrollView и Imageviews без какого-либо успеха. Я также проработал с атрибутом: isScrollContainer без результатов. Кто-нибудь знает, как это сделать? Ура, Лука

Ответы [ 8 ]

33 голосов
/ 17 сентября 2010

@ cV2 Большое спасибо за этот код. Это заставило меня двигаться в нужном мне направлении. Вот моя модифицированная версия, которая перестает прокручивать края изображения ...

    // set maximum scroll amount (based on center of image)
    int maxX = (int)((bitmapWidth / 2) - (screenWidth / 2));
    int maxY = (int)((bitmapHeight / 2) - (screenHeight / 2));

    // set scroll limits
    final int maxLeft = (maxX * -1);
    final int maxRight = maxX;
    final int maxTop = (maxY * -1);
    final int maxBottom = maxY;

    // set touchlistener
    ImageView_BitmapView.setOnTouchListener(new View.OnTouchListener()
    {
        float downX, downY;
        int totalX, totalY;
        int scrollByX, scrollByY;
        public boolean onTouch(View view, MotionEvent event)
        {
            float currentX, currentY;
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    downX = event.getX();
                    downY = event.getY();
                    break;

                case MotionEvent.ACTION_MOVE:
                    currentX = event.getX();
                    currentY = event.getY();
                    scrollByX = (int)(downX - currentX);
                    scrollByY = (int)(downY - currentY);

                    // scrolling to left side of image (pic moving to the right)
                    if (currentX > downX)
                    {
                        if (totalX == maxLeft)
                        {
                            scrollByX = 0;
                        }
                        if (totalX > maxLeft)
                        {
                            totalX = totalX + scrollByX;
                        }
                        if (totalX < maxLeft)
                        {
                            scrollByX = maxLeft - (totalX - scrollByX);
                            totalX = maxLeft;
                        }
                    }

                    // scrolling to right side of image (pic moving to the left)
                    if (currentX < downX)
                    {
                        if (totalX == maxRight)
                        {
                            scrollByX = 0;
                        }
                        if (totalX < maxRight)
                        {
                            totalX = totalX + scrollByX;
                        }
                        if (totalX > maxRight)
                        {
                            scrollByX = maxRight - (totalX - scrollByX);
                            totalX = maxRight;
                        }
                    }

                    // scrolling to top of image (pic moving to the bottom)
                    if (currentY > downY)
                    {
                        if (totalY == maxTop)
                        {
                            scrollByY = 0;
                        }
                        if (totalY > maxTop)
                        {
                            totalY = totalY + scrollByY;
                        }
                        if (totalY < maxTop)
                        {
                            scrollByY = maxTop - (totalY - scrollByY);
                            totalY = maxTop;
                        }
                    }

                    // scrolling to bottom of image (pic moving to the top)
                    if (currentY < downY)
                    {
                        if (totalY == maxBottom)
                        {
                            scrollByY = 0;
                        }
                        if (totalY < maxBottom)
                        {
                            totalY = totalY + scrollByY;
                        }
                        if (totalY > maxBottom)
                        {
                            scrollByY = maxBottom - (totalY - scrollByY);
                            totalY = maxBottom;
                        }
                    }

                    ImageView_BitmapView.scrollBy(scrollByX, scrollByY);
                    downX = currentX;
                    downY = currentY;
                    break;

            }

            return true;
        }
    });

Я уверен, что это можно немного улучшить, но это работает довольно хорошо. :)

28 голосов
/ 21 июня 2010

Я так долго искал этот Код, поэтому я хотел поделиться этим великим миром кода:

этот код из Деятельности, у которой xml файл на бэкэнде , содержащее и ImageView под названием 'img'

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/img"
    android:scaleType="center"
    android:background="#fff"
    android:src="@drawable/picName"
/>

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.xml_name_layout);

    final ImageView switcherView = (ImageView) this.findViewById(R.id.img);

    switcherView.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View arg0, MotionEvent event) {

            float curX, curY;

            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    mx = event.getX();
                    my = event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    curX = event.getX();
                    curY = event.getY();
                    switcherView.scrollBy((int) (mx - curX), (int) (my - curY));
                    mx = curX;
                    my = curY;
                    break;
                case MotionEvent.ACTION_UP:
                    curX = event.getX();
                    curY = event.getY();
                    switcherView.scrollBy((int) (mx - curX), (int) (my - curY));
                    break;
            }

            return true;
        }
    });

}

отлично справилось со мной ... горизонтальная и вертикальная прокрутка включена (включено)

единственная отрицательная сторона ... вы можете прокрутить край изображения ... но это не проблема для меня ... и потратить некоторое время на то, чтобы легко реализовать эту функцию:)

удачи && весело

17 голосов
/ 11 ноября 2014

вот как я это исправил: p

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawVerticalTrack="true" >

<ImageView
    android:contentDescription="Specs"
    android:adjustViewBounds="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:src="@drawable/specs" >
</ImageView>

8 голосов
/ 16 апреля 2012

@ wirbly Большое спасибо за ваш код, он работает именно так, как я хочу.Но когда я впервые прочитал ваш код, я был немного озадачен четырьмя переменными, которые вы забыли определить.

Итак, я хочу добавить определение для кода, чтобы сделать его более понятным.

Resources res=getResources();
Bitmap mBitmap = BitmapFactory.decodeResource(res, R.drawable.p_1920x1080); 
BitmapDrawable bDrawable = new BitmapDrawable(res, mBitmap);

//get the size of the image and  the screen
int bitmapWidth = bDrawable.getIntrinsicWidth();
int bitmapHeight = bDrawable.getIntrinsicHeight();
int screenWidth = this.getWindowManager().getDefaultDisplay().getWidth();  
int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();

Надеюсь, это полезно.

6 голосов
/ 17 июня 2010

Самый простой способ - использовать веб-представление и загрузить в него изображение через локальный HTML-файл.Таким образом, вы также автоматически получите элементы управления масштабированием, если хотите их использовать.Для большого изображения (например, шириной 1000 или 3000 пикселей) вы заметите, что Android (Coliris) не очень хорошо отображает большие увеличенные изображения с высокой четкостью, даже если исходные изображения четкие и несжатые).Это известная проблема.Решение для этого состоит в том, чтобы разбить большое изображение на меньшие плитки и соединить их снова через html (div или table).Я использую этот подход, чтобы предоставить карту метро (больше, чем экран и прокручиваемый) пользователю.

    WebView webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);

    webView.loadUrl( "content://com.myapp.android.localfile/sdcard/myappdata/common/mtr_map.html");

Это может работать для большинства случаев / «обычных приложений», хотя зависит от вашего конкретного случая.Если вы говорите об изображении как прокручиваемом фоне игры, оно может оказаться бесполезным для вас.

Вместо HTML-файла вы также можете загрузить изображение напрямую (png, jpg).Если вы не хотите управлять зумом, просто отключите их.

2 голосов
/ 12 июля 2011

Другой способ - создать HorizontalScrollView, добавить в него imageView, а затем добавить HorizontalScrollView в ScrollView. Это позволяет вам прокручивать вверх, вниз, влево, вправо.

1 голос
/ 14 июля 2016

у меня работает

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/img"
            android:scaleType="centerCrop"
            android:adjustViewBounds="true"/>

        <Button
            style="@style/btn"
            android:id="@+id/btn"
            android:layout_height="60dp"
            android:layout_marginTop="20dp"
            android:background="@drawable/btn"
            android:onClick="click"
            android:text="text" />
    </LinearLayout>

</ScrollView>
0 голосов
/ 17 ноября 2011

Эй, ребята, нашли простое и 100% надежное решение, как упомянул выше мистер Х (так как другие упомянутые коды не работали на некоторых устройствах и не ломались) Просто используйте ScrollView, предоставляемый Android, и он позаботится о вещах

как то так

<ScrollView android:layout_width="fill_parent" android:id="@+id/scrollView1"
        android:layout_height="wrap_content" android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" android:layout_above="@+id/button1"
        android:layout_alignParentRight="true" android:scrollbarAlwaysDrawVerticalTrack="true">
        <LinearLayout android:id="@+id/linearLayout1"
            android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal">
            <ImageView android:src="@android:drawable/ic_menu_report_image"
                android:layout_height="wrap_content" android:id="@+id/imageView1"
                android:layout_width="wrap_content"></ImageView>
        </LinearLayout>
    </ScrollView>

и создать что-то подобное

if (mImageName != null) {
        InputStream is = null;
        try {
            is = this.getResources().getAssets().open("mathematics/"+mImageName);
        } catch (IOException e) {
        }
        Bitmap image = BitmapFactory.decodeStream(is);

        mImageView.setImageBitmap(image);
}

ура!

...