简体   繁体   English

在Android中以编程方式创建的可绘制对象适合父母的宽度并具有成比例的高度

[英]Make a drawable in Android created programmatically fits parent's width and has proportional height

So I am loading images from URLs with this method 所以我用这种方法从URL加载图像

public Drawable loadImage(String url) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        System.out.println(e.getMessage()+" oh noo ");
        return null;
    }
}

But I want the image's width to be the same as its parent (that is the root element with height and width 100%). 但我希望图像的宽度与其父图像相同(即高度和宽度为100%的根元素)。 I couldn't find a way to do it using only XML. 我找不到仅使用XML的方法。 It always leaves paddings on the edges. 它总是在边缘留下填充物。 And I found out it is because the image doesn't have the same ratio of the screen. 我发现这是因为图像的屏幕比例不同。 screen is, for example 16:9 and image is 4:3. 屏幕是例如16:9,图像是4:3。 Android will make paddings to fill this difference. Android将填充以弥补这一差异。

Do you know how can I do it programmatically when I load the image? 您知道在加载图像时如何以编程方式进行操作吗? And I need this image to remain as big as the screen's width even when the device rotates (so I think I will need to calculate it gain) 而且即使设备旋转,我也需要使该图像保持与屏幕宽度一样大(所以我想我需要计算它的增益)

I am using this code to get the size of the screen 我正在使用此代码来获取屏幕的大小

public Size getScreenSize(){
    Size screenSize = new Size();

    DisplayMetrics metrics = new DisplayMetrics();
    this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

    screenSize.height = metrics.heightPixels;
    screenSize.width = metrics.widthPixels;

    return screenSize;
}

public class Size{
    public double height;
    public double width;
}

@EDIT1 @ EDIT1

This is how I insert the drawable in the View. 这就是我在视图中插入可绘制对象的方式。 The view is already declared in the activity's XML 该视图已在活动的XML中声明

ImageView picture = (ImageView) findViewById(R.id.picture);

picture.setImageDrawable(loadImage(url));

@EDIT2 @ EDIT2

this is how I wrote the activity layout and its style 这就是我写活动布局及其样式的方式

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <!-- style="@style/globalHeader" -->
    <LinearLayout
        style="@style/globalHeader"  
        >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#fff"
            android:textSize="18sp"
            android:textStyle="bold"        
            />

        <TextView
            android:id="@+id/subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#fff"
            android:textSize="14sp"
            />

    </LinearLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
            android:id="@+id/picture"
        android:adjustViewBounds="true"
            android:scaleType="centerCrop"
        android:background="#f00"
        >
    </ImageView>

    <TextView
        android:id="@+id/desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        />

    <TextView
        android:id="@+id/details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

This is the appearance I want to achieve 这是我想要达到的外观

https://docs.google.com/a/uniriotec.br/file/d/0B2abPynX9PhkODhRVEkwcUphY28/edit?pli=1 https://docs.google.com/a/uniriotec.br/file/d/0B2abPynX9PhkODhRVEkwcUphY28/edit?pli=1

I think so this is the one you are finding for. 我认为这就是您正在寻找的那个。 just rescale the image of drawable taken from internet. 只是重新缩放从互联网拍摄的可绘制图像的比例。

Bitmap bit = BitmapFactory.decodeResource(getApplicationContext()
                .getResources(), drawable);
        if (bit != null) {
            Bitmap resizedBitmap = Bitmap.createScaledBitmap(bit, width,
                    height, true);
            imageView.setBitmap(resizedBitmap);
            }

the width and height are calculated below 宽度和高度计算如下

    DisplayMetrics disp = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(disp);

    int width = disp.widthPixels;
    int height = disp.heightPixels;

@EDIT @编辑

private Bitmap loadImage(String URL)
{        

    Bitmap bitmap = null;
    InputStream in = null;        
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return bitmap;                
}
private InputStream OpenHttpConnection(String urlString)
        throws IOException
        {
            InputStream in = null;
            int response = -1;

            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();

            if (!(conn instanceof HttpURLConnection))                    
                throw new IOException("Not an HTTP connection");

            try{
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                response = httpConn.getResponseCode();                
                if (response == HttpURLConnection.HTTP_OK) 
                {
                    in = httpConn.getInputStream();                                
                }                    
            }
            catch (Exception ex)
            {
                throw new IOException("Error connecting");            
            }
            return in;    
}

Directly take the bitmap image and rescale it and use it. 直接获取位图图像并重新缩放并使用它。

Not sure how will it behave with device rotation, but I believe you actually can do it from your xml layout, setting your ImageView.ScaleType to CENTER_CROP should do the trick.- 不知道它在设备旋转时的行为如何,但是我相信您实际上可以从xml布局中做到这一点,将ImageView.ScaleType设置为CENTER_CROP应该可以解决问题。

CENTER_CROP : Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). CENTER_CROP:统一缩放图像(保持图像的宽高比),以使图像的两个尺寸(宽度和高度)都等于或大于视图的相应尺寸(减去填充)。

<ImageView
    android:id="@+id/picture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop" />

Try this 尝试这个

<ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:id="@+id/picture"
        android:scaleType="fitXY"
        android:background="#f00"
        >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM