简体   繁体   中英

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

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%). I couldn't find a way to do it using only 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. Android will make paddings to fill this difference.

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

This is how I insert the drawable in the View. The view is already declared in the activity's XML

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

picture.setImageDrawable(loadImage(url));

@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

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.-

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).

<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"
        >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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