I saw many questions on this same topic and tried by using
android:adjustViewBounds="true"
android:scaleType="fitCenter"
still my image is displaying as it is.If I change the
android:scaleType="fitCenter"
to
fitXY working fine.But as per document this one not maintains aspect ratio.So How can I change the code to work as expected?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/card"
android:layout_marginTop="25dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/card" >
<ImageView
android:id="#+id/idImage"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_margin="10dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/783454" />
</LinearLayout>
</LinearLayout>
![enter image description here][1]
![enter image description here][2]
Where iam missing the concept?
Please look at this code, this is how I was scaling bitmaps to fit screen properly. Maybe it will be helpful and give you ideas regarding to your task.
private void loadImage() {
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap imageBitmap = ... load original image bitmap;
Bitmap scaledBitmap = imageBitmap;
// Scaling
int imgSrcHeight = imageBitmap.getHeight();
int imgSrcWidth = imageBitmap.getWidth();
int scaledHeight = 0;
int scaledWidth = 0;
int ctnrHeight = imageView.getMeasuredHeight();
int ctnrWidth = imageView.getMeasuredWidth();
int mHeight = imgSrcHeight - ctnrHeight;
int mWidth = imgSrcWidth - ctnrWidth;
if(mHeight > 0 && mWidth > 0)
{
if(mHeight > mWidth)
{
// scale to fit height
if(mHeight > 0)
{
scaledHeight = ctnrHeight;
// if height < 0 it means it's already inside of content
int coefOverhight = (ctnrHeight * 100)/imgSrcHeight;
scaledWidth = (int)(imgSrcWidth * ((coefOverhight)/100.0));
}
}
else
{
// scale to fit width
if(mWidth > 0)
{
scaledWidth = ctnrWidth;
int coefOverwidth = (ctnrWidth * 100)/imgSrcWidth;
scaledHeight = (int)(imgSrcHeight * ((coefOverwidth)/100.0));
}
}
}
else
{
scaledHeight = imgSrcHeight;
scaledWidth = imgSrcWidth;
}
scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, scaledWidth, scaledHeight, true);
imageView.setImageBitmap(scaledBitmap);
}
Related
Hi guys I am trying to build a layout but I am not able to understand how to build it
what I am trying to do is to add a Image whose height and width will be of screen size and below it will be a description about the Image which the users can view when they scroll it but the whole screen will be consisting of image only until the user scrolls the text below will not be displayed
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:fillViewport="true"
>
<RelativeLayout
android:layout_weight="1"
android:id="#+id/relativla"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/hamburger"
android:id="#+id/navi"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:background="#drawable/dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/descrpitiondietplan"
android:id="#+id/textView5"
android:layout_below="#+id/imageView"
/>
</RelativeLayout>
</ScrollView>
you can see in the below link the way i want the layout to be
http://postimg.org/image/avgmk6pi3/
please feel free to drop in comments if you need any additional details
EDIT 1
After trying rachel solution I am getting this
http://postimg.org/image/tdb02gu9l/
now as you can see in the image the image view is taking whole width of the screen which is fine but it doesn't take the whole height of the screen if i write match_parent to the imageview layout_height the image takes the whole screen but it doesn't allow me to scroll
It sounds like you'll need to do some work to get the screen size of the device, then set the image view's size programatically using that.
See the accepted answer here for more details on calculating the device screen size: Android Layout, view height is equal to screen size
Finally got it working after a bit of research on google and stackoverflow finally got a way
so here it is first your activity / fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
img = (ImageView) v.findViewById(R.id.imageView);
Drawable drawable = getResources().getDrawable(R.drawable.dp);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
float scalingFactor = this.getBitmapScalingFactor(bitmap);
Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor);
// Set the bitmap as the ImageView source
this.img.setImageBitmap(newBitmap);
return v;
}
private float getBitmapScalingFactor(Bitmap bm) {
// Get display width from device
int displayWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
// Get margin to use it for calculating to max width of the ImageView
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)this.img.getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int rightMargin = layoutParams.rightMargin;
// Calculate the max width of the imageView
int imageViewWidth = displayWidth - (leftMargin + rightMargin);
// Calculate scaling factor and return it
return ( (float) imageViewWidth / (float) bm.getWidth() );
}
as i am using fragment I have onCreateView onCreate will be for people using activity
and create a Utils class
public class Util {
public static Bitmap ScaleBitmap(Bitmap bm, float scalingFactor) {
int scaleHeight = (int) (bm.getHeight() * scalingFactor);
int scaleWidth = (int) (bm.getWidth() * scalingFactor);
return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
}
if you guys have a better solution do let me know
These is the result that I am after:
Basically I want to scale the 3 images so that they have the same height and all together fill the screen width. The original images will all have same height.
Can this be done using layout, without width calculations from code?
Just use Layout Weights.
In the main layout, or the layout which contains the ImageViews, put
android:weightSum="10"
and then in the individual ImageViews, put layout_weights as shown below, or upto your requirements.
This basically means the width of the images will be 25%, 55% and 20% respectively.
You can use a linear layout with weight attribute specified as shown below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="0dp"
android:src="#drawable/bg_canvas"
android:layout_height="300dp"
android:layout_weight="0.33"/>
<ImageView
android:layout_width="0dp"
android:src="#drawable/bg_canvas"
android:layout_height="300dp"
android:layout_weight="0.33"/>
<ImageView
android:layout_width="0dp"
android:layout_height="300dp"
android:src="#drawable/bg_canvas"
android:layout_weight="0.33"/>
</LinearLayout>
Comment below if you need any further info
try this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
.../>
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
.../>
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
.../>
</LinearLayout>
the "magic" is in the weight component. you define a total weight of 3 in the layout and your image views should take a third of it, so the value is 1.
For my case the images needed to be updated at runtime, so none of the answers were exact fit.
I ended up extending LinearLayout and writing a small routine that unifies all images heights and make sure that all images together fill the LinearLayout width. In case someone is trying to achieve the same, my code looks like this:
public class MyImgLayout extends LinearLayout
{
public MyImgLayout(Context context)
{
super(context);
}
public void setup(ArrayList<String> images)
{
this.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
this.setLayoutParams(layoutParams); //set 0 height until we calculate it in onMeasure
for (String image : images) {
ImageView ivArticle = new ImageView(getContext());
setImageFromName(image, ivArticle); //this where you set the image
this.addView(ivArticle);
}
}
private void scaleImages()
{
if(getMeasuredHeight() == 0 && getMeasuredWidth() > 0) {
if (isHorizontal) {
double childRatioSum = 0;
int images = 0;
for (int i = 0; i < getChildCount(); i++) {
ImageView iv = (ImageView) getChildAt(i);
double width = iv.getDrawable().getIntrinsicWidth();
double height = iv.getDrawable().getIntrinsicHeight();
if (height > 0) {
childRatioSum += width / height;
images++;
}
}
if (childRatioSum > 0 && images == getChildCount()) {
//all images are downloaded, calculate the container height
//(add a few pixels to makes sure we fill the whole width)
double containerHeight = (int) (getMeasuredWidth() / childRatioSum) + images * 0.5;
for (int i = 0; i < getChildCount(); i++) {
ImageView iv = (ImageView) getChildAt(i);
double width = iv.getDrawable().getIntrinsicWidth();
double height = iv.getDrawable().getIntrinsicHeight();
iv.setLayoutParams(new LinearLayout.LayoutParams((int) (width * (containerHeight / height)), (int) containerHeight));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) this.getLayoutParams();
params.width = LayoutParams.MATCH_PARENT;
params.height = (int) containerHeight;
this.setLayoutParams(params);
requestLayout();
}
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
scaleImages();
}
}
How can I cut rectangular image (600 x 300) from left and right to fit in square ImageView ? I don't want to resize image, I just want to crop it, to be 300 x 300.
[SOLUTION]
As #blackbelt said
Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
is great for cropping images. So how can you automatically crop images with different sizes. I create this simple code for that:
// From drawable
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
// From URL
Bitmap src = null;
try {
String URL = "http://www.example.com/image.jpg";
InputStream in = new java.net.URL(URL).openStream();
src = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
int width = src.getWidth();
int height = src.getHeight();
int crop = (width - height) / 2;
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height);
ImageView.setImageBitmap(cropImg);
Expanding a little on the answer above
Since in some situations you can end up with an exception or not the expected result, just by using the Bitmap.createBitmap(), like the fallowing:
java.lang.IllegalArgumentException: x + width must be <=
bitmap.width()
Heres is a small function that does the crop and handle some of the commons cases.
Edit: updated accordantly to droidster's claim.
public static Bitmap cropToSquare(Bitmap bitmap){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width)? height - ( height - width) : height;
int cropW = (width - height) / 2;
cropW = (cropW < 0)? 0: cropW;
int cropH = (height - width) / 2;
cropH = (cropH < 0)? 0: cropH;
Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
return cropImg;
}
I did several testing with some images of different resolutions and sizes and it work as expected.
It can also be used in other situations, for example when you are trying to make a "perfectly" round image and need to pass a squarish bitmap, etc.
set fixed image view height, width, and set two properties to image view
android:adjustViewBounds="true"
android:scaleType="centerCrop"
done
You can use
Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);
from the documentation:
Returns an immutable bitmap from the specified subset of the source
bitmap. The new bitmap may be the same object as source, or a copy may
have been made. It is initialized with the same density as the
original bitmap.
Here you can find the documentation
Now xml is having properties like
custom:cropAspectRatioX="2"
custom:cropAspectRatioY="1"
Make both 1 if u want square cropping. now it is of rectangle
Add activity CropActivity
package agropost.post.agro.com.agropost.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.widget.Button;
import com.theartofdev.edmodo.cropper.CropImageView;
import agropost.post.agro.com.agropost.R;
import agropost.post.agro.com.agropost.Utility.Constants;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class CropActivity extends AppCompatActivity {
public static boolean isCrop = false;
#BindView(R.id.img_crop)
CropImageView imgCrop;
#BindView(R.id.btn_done)
Button btnDone;
#BindView(R.id.btn_cancel)
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
ButterKnife.bind(this);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
width = width - 80;
imgCrop.getLayoutParams().height = width;
imgCrop.getLayoutParams().width = width;
imgCrop.setBackground(null);
imgCrop.setScaleType(CropImageView.ScaleType.FIT_CENTER);
imgCrop.setImageBitmap(Constants.mDashboardActivity.thumbnail_r);
}
#OnClick(R.id.btn_done)
public void onViewClicked() {
isCrop = true;
Intent returnIntent = new Intent();
Constants.mDashboardActivity.thumbnail_r = imgCrop.getCroppedImage();
setResult(3, returnIntent);
finish();
}
#OnClick(R.id.btn_cancel)
public void onViewClickedCancel() {
byte[] byteArray = getIntent().getByteArrayExtra("default");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Constants.mDashboardActivity.thumbnail_r = bmp;
isCrop = true;
Intent returnIntent = new Intent();
setResult(3, returnIntent);
finish();
}
#Override
public void onBackPressed() {
// super.onBackPressed();
}
}
xml of activity..............
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent"
android:gravity="center"
android:orientation="vertical"
tools:context=".Activity.CropActivity">
<com.theartofdev.edmodo.cropper.CropImageView xmlns:custom="http://schemas.android.com/apk/res-auto"
android:id="#+id/img_crop"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#drawable/drawer_bg"
android:scaleType="centerInside"
custom:cropAspectRatioX="2"
custom:cropAspectRatioY="1"
custom:cropFixAspectRatio="true"
custom:cropShape="rectangle" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btn_done"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="#dimen/margin_40"
android:layout_marginRight="#dimen/margin_20"
android:layout_marginTop="#dimen/margin_20"
android:layout_weight="1"
android:background="#drawable/btn_bg_green_rounded"
android:text="Done"
android:textColor="#color/colorWhite"
android:textSize="#dimen/fontsize_normal" />
<Button
android:id="#+id/btn_cancel"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_40"
android:layout_marginTop="#dimen/margin_20"
android:layout_weight="1"
android:background="#drawable/btn_bg_green_rounded"
android:text="Cancel"
android:textColor="#color/colorWhite"
android:textSize="#dimen/fontsize_normal"
android:visibility="gone" />
</LinearLayout>
</LinearLayout>
add dependecy
implementation 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
Please look at this code fragment:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingBottom="35dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="5dp"
android:scaleType="fitXY"
android:src="#drawable/1" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="5dp"
android:scaleType="fitXY"
android:src="#drawable/2" />
</LinearLayout>
</LinearLayout>
I'm using this code in my Android app, based mainly on images. I have a problem with proper scaling. When I'm using scaleType="fitXY" (code above), everything on all dimensions looks fine, but not images' height. Width is properly stretched, but height not. I tried to use centerInside which doesn't stretch my images and keeps ratio okay. But then there's a problem with images' size - they're just too small on some devices. My question is - how to make an image-based app look the same (or very close) on all devices?
Samples:
http://i.stack.imgur.com/cjS5f.jpg
width and height ok, but margins are messed up, fitCenter
http://i.stack.imgur.com/4BUTr.jpg
width is okay - but height not, fitXY
try replacing
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:scaleType="fitXY"
by
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:scaleType="centerInside"
Since you seem to be trying to fill the screen horizontally, this would stretch the images across the screen as much as possible without distorting them
If you have a sort of background which you can crop and just want to fit horizontally try
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:scaleType="center"
If you want to preserve the height/width ratio of the original image you can do it at run-time.
Since you want for your ImageButton android:layout_width="fill_parent" android:layout_height="wrap_content" you can adapt the following code:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // just compute size, don't create bitmap
BitmapFactory.decodeStream(stream, null, options); // stream is the InputStream representing the image you want to display
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
imageViewWidth = imageView.getWidth(); // imageView is the View container for the image you want to display
imageViewHeight = imageView.getHeight();
// Compute the sample size
double sampleSize = computePowerOfTwoInSampleSize(options, imageViewWidth, imageViewHeight);
if(sampleSize<1) {
options.inSampleSize = 1;
}
else {
options.inSampleSize = (int) sampleSize;
}
options.inJustDecodeBounds = false; // compute size and create bitmap
bitmap = BitmapFactory.decodeStream(stream, null, options);
imageView.setImageBitmap(bitmap);
try {
stream.close();
}
catch (IOException e) {
e.printStackTrace();
}
where the method computePowerOfTwoInSampleSize is something like this (take into consideration that resizing to power of 2 is more efficient compared to other values):
private double computePowerOfTwoInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
int height = options.outHeight;
int width = options.outWidth;
double inSampleSize = 1;
// compute the up-sample coefficient (power of 2)
if(height < reqHeight && width < reqWidth) {
while(height < reqHeight && width < reqWidth) {
height = height*2;
width = width*2;
if(height < reqHeight && width < reqWidth) {
inSampleSize = inSampleSize/2;
}
}
}
// compute the down-sample coefficient
else {
while(height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width (power of 2)
height = Math.round((float)height/2);
width = Math.round((float)width/2);
inSampleSize = inSampleSize*2;
}
}
return inSampleSize;
}
You should set it scaleType as Matrix and scale it to the closest side(top and bottom or left and right) keeping the aspect ratio.
I download image and set it as a screen background dynamically using Imageview. I have tried ScaleType, to scale the image.
If image height is larger than width then ScaleTypes fitStart, fitEnd and fitCenter don't work. Android scale down the photo and fit it based on the height, but I see some extra blank space as part of the width.
I want to scale down the photo based on the width so that it fits the width and I don't care if there's some extra blank space as part of the height or if height is too long it is fine if it's going out of the view(if that's possible?).
ScaleType.XY scale the photo and fit everything in the ImageView and doesn't care about image height/weight ratio.
<ImageView
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitStart"
/>
I ended up using this code:
<ImageView
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/name"
/>
Make sure you set the image using src instead of background.
android:adjustViewBounds="true" does the job!
This elegant solution found here will work like a charm for you.
Basically you just have to create a small class that extends ImageView and simply override the onMeasure method to adjust the width and height as you want. Here it scales to fit width by using:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
You would use this special ImageView like this:
<your.activity.package.AspectRatioImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:src="#drawable/test" />
There is a simple method if you simply want to fill the width of screen and have height proportional (and know the ratio of the image) you can do this in OnCreate():
setContentView(R.layout.truppview_activity);
trupImage = (ImageView) findViewById(R.id.trupImage);
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float scWidth = outMetrics.widthPixels;
trupImage.getLayoutParams().width = (int) scWidth;
trupImage.getLayoutParams().height = (int) (scWidth * 0.6f);
Where 0.6 is the ratio adjustment (you could also calc automatically of course if you know the w & h of image).
PS:
Here is the XML side:
<ImageView
android:id="#+id/trupImage"
android:layout_width="match_parent"
android:background="#color/orange"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
if you want to fit the image whole parent block
it will stretch the image
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
And if you want to fit image whole parent with original ratio of image
it will crop out some part of image
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
This works for me.
Create a class extends ImageView
package com.yourdomain.utils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class ResizableImageView extends ImageView {
public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
if (d != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
In xml use the following instead of ImageView
<com.yourdomain.utils.ResizableImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/test" />
I think you cant do it only with XML, you need to resize yourself, the bitmap
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
try {
((ImageView) findViewById(R.id.background))
.setImageBitmap(ShrinkBitmap(width));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
then
private Bitmap ShrinkBitmap(int width)
throws FileNotFoundException {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.img, bmpFactoryOptions);
int widthRatio = (int) android.util.FloatMath
.ceil(bmpFactoryOptions.outWidth / (float) width);
bmpFactoryOptions.inSampleSize = widthRatio;
if (bmpFactoryOptions.inSampleSize <= 0)
bmpFactoryOptions.inSampleSize = 0;
bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.img, bmpFactoryOptions);
return bitmap;
}
And the layout
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>