how to shrink an image in size in android layout? - android

I have an image that I want to display in android layout
but I want to make it proportionally smaller than its original size.
How can I do this?
if I specify some width and height it crops the image instead of shrinking it

Use the scaleType attribute to define the scaling of the ImageView, e.g. :
android:scaleType="fitCenter"
see http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

You can scale the image to 80% size using the below code sample.
int srcWidth = srcBitmap.getWidth();
int srcHeight = srcBitmap.getHeight();
int dstWidth = (int)(srcWidth*0.8f);
int dstHeight = (int)(srcHeight*0.8f);
Bitmap dstBitmap = Bitmap.createScaledBitmap(srcBitmap, dstWidth, dstHeight, true);
Change the multiple value based on the % you need to scale.
Also, refer to this link for more options.
Scaling bitmap to 80 percent

Related

I want to put a bitmap inside imageview keeping aspect ratio

This is my xml code:
<ImageView
android:id="#+id/ColImgPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:adjustViewBounds="true"
android:background="#drawable/border"/>
and this my java code, that it is inside listview:
ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
imageView.setPadding(5, 5, 5, 5);
imageView.setVisibility(View.VISIBLE);
try {
Bitmap bmp = ((Bitmap) MyArrList.get(position).get("ImageThumBitmap"));
int bmpx = bmp.getWidth();
int bmpy = bmp.getHeight();
Log.i("INFO","X: "+bmpx+" Y: "+bmpy);
Bitmap photobitmap1 = Bitmap.createScaledBitmap(bmp, bmpx/2,bmpy/2, true);
imageView.setImageBitmap(photobitmap1);
//imageView.setImageBitmap((Bitmap) MyArrList.get(position).get("ImageThumBitmap"));
} catch (Exception e) {
// When Error
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
The problem is that I want to put the bitmap resized into bitmap but the imageview always appears squared.
The size of the bitmap is: X: 4160 Y: 3120 and the screen size is : WIDTH= 1080 HEIGHT= 1776
I want to put the width fill parent and resize the height keeping the aspect ratio. I tried some xml alternatives like `ScaleType.
Someone knows the way to put correctly the bitmap?
Does fitXy not work for the scale type?
http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
It's an ImageView so you need to use android:src="#drawable/border" instead of android:background. Also try android:scaleType="fitXY" or cropCenter.
There are different Scale Type Available in Android ImageView
CENTER_INSIDE - used to set Bitmap with keeping bitmap original aspect ratio.
CENTER_CROP - used to set Bitmap in imageview to cover imageview without broken aspect Ratio , rather bitmap set from negative x , y value to cover imageview area.
FIT_XY - used to set whole bitmap into available ImageView height and width means bitmap takes Imageviews Aspect Ratio.
OR
if you want to resize bitmap then take height or width which you want to set and take ratio of height / width if take width or take width/ height if you have next height and multiply repetitive width and height to this ratio .It will change height and width of bitmap but keep Aspect Ratio of original Bitmap .

How to maintain the aspect ratio of the image if imageview first stretch to fill parent

I want to stretch the image to fill width and adjust the height according to width and maintain the aspect ratio. I want it should cover entire width (fillparent) and height of imageview should adjust like in way so that aspect ratio is maintained.
I tried fit_xy but not working in my case. Please help me
There can two possible workarounds even if you set the scale type fit_xy
1) By default Android will scale your image down to fit the ImageView, maintaining the aspect ratio. However, make sure you're setting the image to the ImageView using android:src="..." rather than android:background="...". src= makes it scale the image maintaining aspect ratio, but background= makes it scale and distort the image to make it fit exactly to the size of the ImageView. (You can use a background and a source at the same time though, which can be useful for things like displaying a frame around the main image, using just one ImageView.)
2)You should also see android:adjustViewBounds to make the ImageView resize itself to fit the rescaled image. For example, if you have a rectangular image in what would normally be a square ImageView, adjustViewBounds=true will make it resize the ImageView to be rectangular as well. This then affects how other Views are laid out around the ImageView.
you can change the way it default scales images using the android:scaleType parameter. By the way, the easiest way to discover how this works would simply have been to experiment a bit yourself! Just remember to look at the layouts in the emulator itself (or an actual phone) as the preview in Eclipse is usually wrong.
I'm not sure when the feature I use was added to the Android SDK but there is a simple solution that does exactly what the OP is looking for:
As expected, set layout:width and layout:height to fill_parent.
As another responder mentioned correctly, use src to find your image, not background.
However instead of trying scaleType of fit_xy (which finds the narrowest side to fit into the view rather than the longest side), use scaleType of centerCrop.
centerCrop will center and fill in the viewport while retaining aspect ratio.
Hope this helps! I used it for the webView loading overlay of a commercial app I developed for my current employer.
Copy/paste solution: in your activity XML file, add the following lines:
<ImageView
android:id="#+id/logo"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="#drawable/your_image_name"
/>
There are two ways of doing this:
First find the display height and width and call this method
private void scaleImage(int displayWidth) {
// Get the ImageView and its bitmap
width=displayWidth;
Drawable drawing = holder.imagepost.getDrawable();
{
Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();
int bounding = dpToPx(width);
// Determine how much to scale: the dimension requiring less
// scaling is
// closer to the its side. This way the image always stays
// inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by
// the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
height = scaledBitmap.getHeight(); // re-use
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
// Apply the scaled bitmap
holder.imagepost.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.imagepost
.getLayoutParams();
params.width = width;
params.height = height;
holder.imagepost.setLayoutParams(params);
}
}
private int dpToPx(int dp) {
float density = context.getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
Or the Best way i know is to use Android Query
Here is the link http://code.google.com/p/android-query/ and you can download from there itself.Below id the code to maintain the Aspect Ratio
aq.id(R.id.imageView)
.image(imageString, true, true,
displaywidth, 0, null, AQuery.FADE_IN, AQuery.RATIO_PRESERVE);
Below solution is working fine for me.
Use AQuery Libray option "AQuery.RATIO_PRESERVE" to preserve aspect ratio:
aq.id(R.id.imgView).progress(R.id.imgPb).image(url, true, true,150, 0,null,AQuery.FADE_IN,AQuery.RATIO_PRESERVE);
Use below settings for ImageView:
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
Use below settings for auto GridView Columns:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="150dp"/>

Resizing ImageView to fit Image

its a little hard to explain but ill try it anyways.
Im displaying an Image within an ImageView, the imageview is set to use 50% of the ScreenHeight using weight attribute.
Now if the ImageAspectRatio doesnt fit the Ratio of the ImageView, i have an empty space at the bottom and onTop of the ImageView.
Basically i want my ImageView to have a maxSize which is 50% of the ScreenHeight, but to shrink in height if the image in it doesnt use its full height, or at least move to the top of the ImageView.
So, what i did here is i set the View to its max size, and i set the image the way the ImageView usually would. After that i way for the ImageView to layout, then get its Height, as thats the max height i want the View to have.
Then i calculate the Scaling i need to apply. I scale the Image and set the view to Wrap content as it should have the views previous height as a bounding.
Now, this works fine on a Samsung GT-I9000 running CyagenoMod (Android 4.2.2) also tried this on a Kindle HD. But when doing the same on a Nexus 4(running android 4.3) it seems to ignore everything i do.
By that i mean, the image appears to scale properly (imageHeight after scaling something like 53x), but the image takes almost the whole Screen. I dont get why it works on the other 2 devices but on the Nexus.
Is there any new API concerning ImageView for Android 4.3 i dont know about?
#Override
public void setImageResource(final int resId) {
// this.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0.5f));
super.setImageResource(resId);
getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
#Override
public boolean onPreDraw() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int boundingY = getHeight();
int boundingX = getWidth();
float xScale = ((float) boundingX) / width;
float yScale = ((float) boundingY) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
MyImageView.this.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT ));
MyImageView.super.setImageBitmap(scaledBitmap);
getViewTreeObserver().removeOnPreDrawListener(this);
return true;
}
});
}
Ok here is a picture of what im trying to do/doing.
Consider the blueish thing the size of the ImageView, and the Black rectangle, the actual Size of the Image. The Blue size is what i get, if i set the Size of the ImageView to width = matchParent and height = 0 with weight 0.5. This is the MAX Height i want my ImageView to have.
Now, it is possible that the Image has a width >= width of the ImageView. in that case, i want to resize the Height, to fit the Height of the Image, so i resize the Image, to find within those bounds and set the Image to WrapContent as the Image is the exact size i want the View to be.
But this is also possible for an Image. 2*width = height
In that case i dont want the ImageView to do anything. Just Maintain its max height and display the give Image.
This works, as i already said on some devices, GT-I9000 and Amazon Kindle HD, but on a Nexus 4 the images that have a much bigger height than width tend to occupy the whole damn screen.
I debugged this and retrieved ImageViewHeight and BitmapHeight. Both stated that the Image and the ImageView is 534 PX high.
I really dont get why i works on the other 2 devices, but not on the nexus.
<include layout="#layout/own_action_bar" />
<*.view.MyImageView
android:id="#+id/drawFragment_iv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:adjustViewBounds="true"
android:contentDescription="#string/hello" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" >
something in here
<RelativeLayout/>
<LinearLayout/>
call setBackgroundResource instead of setImageResource on your ImageView object and it will scale the image to fit the ImageView.
Although it is not an efficient way ti achieve this but if don't have a lot of such ImageViews this should do the trick.

Problems with the width of the bitmap. The width is limited by the height of the screen

I'm creating a bitmap wich i need to use as background of a 320 width screen. The problem is that the bitmap is not getting the width i want. It is getting two empty spaces on the left and on the right. It is because it is fitting the height of the screen, but i dont want that, i want to force the bitmap to have the width i want. Doesn't matter if a portion of the height of the bitmap is out of the screen.
i need to force the width when i am adding the image to the layout, i mean that the image must be keep the aspect ratio, but the image must be higher than the height of the screen, and the image must be shown incomplete if the heigh of the image is higher than the height of the screen. Now this is not happening, because the layout is forcing the width to respect the image and show all the height of the image in the height of the screen, then i think the problem is on the layout rules
im creating the bitmap with:
View view;
Bitmap aux = Util.loadImage( filename ); //image loaded but with his original width
Bitmap image = Util.scaleBitmap(aux, 320); //scaling to 320
((ImageView)view).setImageBitmap( resource.image );
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( 320 , h );
rlp.addRule( RelativeLayout.CENTER_HORIZONTAL );
rlp.addRule( RelativeLayout.ALIGN_PARENT_TOP );
layout.addView( view , rlp );
What am i doing wrong?
Try using this:
((ImageView)view).setScaleType(ImageView.FitCenter);
To see more options see http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType
Since you don't care about the height you should use CENTER_CROP.
Define the scale type and then set the image.
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).

Scale an image up to fill entire ImageView in Android

I'd like to scale an image up to take up the entire size of an ImageView. This is subtly different than using scaleType=fit_center because fit_center will leave bands around the image if the image aspect ratio does not exactly match the ImageView's aspect ratio. Instead, I would like the image to get centered and scaled up to completely fill the enclosing view, with any excess chopped off.
I'm able to accomplish this by computing my own custom image matrix during onCreate():
final Display display = getWindowManager().getDefaultDisplay();
final float screenWidth = display.getWidth();
final float screenHeight = display.getHeight();
final float imageWidth = splashView.getDrawable().getIntrinsicWidth();
final float imageHeight = splashView.getDrawable().getIntrinsicHeight();
final Matrix splashMatrix = new Matrix();
final float scale = Math.max(screenHeight/imageHeight,screenWidth/imageWidth);
splashMatrix.postScale( scale, scale );
splashView.setImageMatrix(splashMatrix);
This works fine, but it seems like there must be an easier away. Does anyone know of a way to scale up an image in an ImageView while both preserving the aspect ratio of the image and fully filling in the ImageView?
(Note: in my case my ImageView is taking up the full screen, so I use getWindowManager().getDisplay() to find the desired image size. You can't use splashView.getWidth()/getHeight() because the view hasn't been laid out yet and doesn't have a size)
You can use android:scaleType="centerCrop".
Keeps the aspect ratio and scales the image just like you want it.
For more information please go through the below link
http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType
In some cases all you need is
android:adjustViewBounds="true"
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
This worked for me to fit the image inside the whole image view, plus it make sense that it says "ScaleType.FIT_XY" to fit the X and Y axis of the imageView.
From the xml file it would be:
android:scaleType="fitXY"
Try scaleType attribute for your ImageView. http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType
I am very late but hope it helps in the future. Here is my solution to how to stretch the image to full screen or image view without scaleType="fitXY" as it causes damage to the image. Use the following library.
[A simple imageview which scales the width or height aspect with the given ratio]
https://github.com/santalu/aspect-ratio-imageview
To Find the aspect ratio of the device screen use the following Code.
DisplayMetrics metrics =this.getResources().getDisplayMetrics();
float ratio = ((float)metrics.heightPixels / (float)metrics.widthPixels);
you must set android:scaleType="centerCrop" to fill entire screen
but you noticed that scaletype property worked together with android:layout_width and android:layout_height property.
you must set to match_parent

Categories

Resources