我正在尝试显示来自URL的图像,该图像可能比屏幕尺寸大。我有点工作,但是我希望它可以扩展以适合屏幕,并且当屏幕方向更改时,我也有问题。图像很小,我希望它也将其宽度缩放到屏幕上。 (在这两种情况下,我都希望图像用滚动条填充屏幕宽度(如有必要为高度)。

这是我的图像视图:

<ImageView android:id="@+id/ImageView01" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true">
</ImageView>

这是加载图像的Java代码:(为简单起见,删除了一些错误处理代码)

    Object content = null;
    try{
      URL url = new URL("http://farm1.static.flickr.com/150/399390737_7a3d508730_b.jpg");
      content = url.getContent();
    }
      catch(Exception ex)
    {
        ex.printStackTrace();
    }
    InputStream is = (InputStream)content;
    Drawable image = Drawable.createFromStream(is, "src");
    Image01.setImageDrawable(image);

我尝试了Android:ScaleType的不同设置。很抱歉,如果以前问这个问题。我已经浏览了有关该主题的许多教程,但它们似乎对我不起作用。不确定它是否与图像的加载方式有关。 (来自网络而不是本地资源)

另一个问题是,有时图像甚至不会加载。没有运行时错误,我只是在ImageView中什么都没有。

请让我知道您是否需要更多信息或澄清。

有帮助吗?

解决方案

关于“有时图像甚至没有加载”的问题与上下文有关,因此我使用此功能来解决该问题

public Object fetch(String address) throws MalformedURLException,
    IOException {
        URL url = new URL(address);
        Object content = url.getContent();
        return content;
    }  

    private Drawable ImageOperations(Context ctx, String url) {
        try {
            InputStream is = (InputStream) this.fetch(url);
            Drawable d = Drawable.createFromStream(is, "src");
            return d;
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }

因此,要用图像填充屏幕宽度,您必须有这样的代码

    try{
        String url = "http://farm1.static.flickr.com/150/399390737_7a3d508730_b.jpg";           
        Drawable image =ImageOperations(this,url);
        Image01.setImageDrawable(image);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }


    Image01.setMinimumWidth(width);
    Image01.setMinimumHeight(height);

    Image01.setMaxWidth(width);
    Image01.setMaxHeight(height);

更新::如果您显然加载了大尺寸的图像,则必须等待更多时间,并且下载问题可能会引起unkosthostexception。

是的,您是对的,您将在本地保存图像,本地访问比下载快。

为了避免旋转上的问题,更改设置了您的configchanges =“键盘隐藏|方向”属性。

<activity android:name=".myActivity"
...
         android:configChanges="keyboardHidden|orientation"   >
...
/>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top