I have TextView with drawableLeft & drawableRight in List item.
The problem is, whenever the height of TextView is larger, drawableLeft & drawableLeft didn't automatically scale based on the height of the TextView.
Is it possible to scale the height of drawableLeft & drawableRight in TextView ?
(I was using 9 patch image)
This might help you out.
There are two properties scaleX and scaleY
The code below will scale down the image and the text with 30%.
Therefore you have to increase the font size with that many "sp", so that when it get re-sized (scaled) it would fit the "sp" you prefer.
Example. If I set the font to 18, then 30% out of 18 is 5.4sp, so roughly, this is the value I am targeting at, because when it gets scaled, it would become 13sp
<TextView
android:textSize="18sp"
android:scaleX="0.7"
android:scaleY="0.7"
The last thing to do is set the CompundDrawable.
tview.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.xxx), null, null, null);
Wrap your resource in a drawable that defines your desired size similar to:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:drawable="#drawable/icon"
android:width="#dimen/icon_size"
android:height="#dimen/icon_size" />
</layer-list >
After that, use this drawable in your textview tag
Hope this help
Textview tv = (TextView) findViewById(R.id.tv_dummy)
int imageResource = R.mipmap.ic_image;
Drawable drawable = ContextCompat.getDrawable(context, imageResource);
int pixelDrawableSize = (int)Math.round(tv.getLineHeight() * 0.7); // Or the percentage you like (0.8, 0.9, etc.)
drawable.setBounds(0, 0, pixelDrawableSize, pixelDrawableSize); // setBounds(int left, int top, int right, int bottom), in this case, drawable is a square image
tv.setCompoundDrawables(
null, //left
null, //top
drawable, //right
null //bottom
);
The only acceptable answer here should be to use an ImageView with the scaleTypes as per usual. Hacky work arounds to scale an image on a TextView that isn't supported by Android seems.. unnecessary. Use the SDK as it was intended.
I solved an equivalent usecase by introducing a ScaleDrawable and overriding its .getIntrisicHeight() so that it is at least the TextView height. The TextView.addOnLayoutChangeListener part, required to rebind the Drawable on a TextView size change works with API11+
Drawable underlyingDrawable =
new BitmapDrawable(context.getResources(), result);
// Wrap to scale up to the TextView height
final ScaleDrawable scaledLeft =
new ScaleDrawable(underlyingDrawable, Gravity.CENTER, 1F, 1F) {
// Give this drawable a height being at
// least the TextView height. It will be
// used by
// TextView.setCompoundDrawablesWithIntrinsicBounds
public int getIntrinsicHeight() {
return Math.max(super.getIntrinsicHeight(),
competitorView.getHeight());
};
};
// Set explicitly level else the default value
// (0) will prevent .draw to effectively draw
// the underlying Drawable
scaledLeft.setLevel(10000);
// Set the drawable as a component of the
// TextView
competitorView.setCompoundDrawablesWithIntrinsicBounds(
scaledLeft, null, null, null);
// If the text is changed, we need to
// re-register the Drawable to recompute the
// bounds given the new TextView height
competitorView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
competitorView.setCompoundDrawablesWithIntrinsicBounds(scaledLeft, null, null, null);
}
});
I did not found way. But that you show looks like a list of items. Each item would be a LinearLayout horizontal with imagesView from left to right and text in center. The image dimension do a android:scaleType="fitXY" for ajust the size height to the textview height.
If you want no deform de image use scaleType="CENTER_INSIDE". http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
<LinearLayout
android:layout_width="fill_parent"
android:id="#+id/HeaderList"
android:layout_gravity="top"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/backImg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:background="#color/blancotransless"
android:src="#drawable/header"
android:scaleType="fitXY" >
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/NameText"
android:text="The time of prayer"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingLeft="4dp"
android:paddingTop="4dp"
/>
<ImageView
android:id="#+id/backImg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:background="#color/blancotransless"
android:src="#drawable/header"
android:scaleType="fitXY" >
</ImageView>
</LinearLayout>
Another approach to create a custom size for the drawable inside the TextView is by using the BindingAdapter. Using this, you will be able to set you image size in your xml.
For example, TextViewBindingAdapter.java
public class TextViewBindingAdapter {
#BindingAdapter({"android:imageSize"})
public static void bindIconSize(TextView textView, int size) {
Drawable[] drawables = textView.getCompoundDrawables();
if(drawables[0] != null) {
drawables[0].setBounds(0, 0, size, size); // setBounds(int left, int top, int right, int bottom), in this case, drawable is a square image
textView.setCompoundDrawables(
drawables[0], //left
null, //top
null, //right
null //bottom
);
}
if(drawables[1] != null) {
drawables[1].setBounds(0, 0, size, size); // setBounds(int left, int top, int right, int bottom), in this case, drawable is a square image
textView.setCompoundDrawables(
null, //left
drawables[1], //top
null, //right
null //bottom
);
}
if(drawables[2] != null) {
drawables[2].setBounds(0, 0, size, size); // setBounds(int left, int top, int right, int bottom), in this case, drawable is a square image
textView.setCompoundDrawables(
null, //left
null, //top
drawables[2], //right
null //bottom
);
}
if(drawables[3] != null) {
drawables[3].setBounds(0, 0, size, size); // setBounds(int left, int top, int right, int bottom), in this case, drawable is a square image
textView.setCompoundDrawables(
null, //left
null, //top
null, //right
drawables[3] //bottom
);
}
}
}
Now, in your .xml you can set the android:imageSize.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:drawableLeft="#drawable/alpha_s_circle"
android:drawablePadding="4dp"
android:gravity="center_vertical"
android:textSize="16sp"
android:imageSize="#{300}"/>
And don't forget to set in your gradle.build this code below:
android {
....
buildFeatures {
dataBinding = true
}
}
Just make 9-path background repeating this pattern.
And also it seems it will be better look in case the pattern will be applied to the list, not to individual item.
I think the cleanest solution would be to override TextView. Here's an example:
https://gist.github.com/hrules6872/578b52fe90c30c7445a2
I changed a bit:
private void resizeCompoundDrawables() {
Drawable[] drawables = getCompoundDrawables();
if (compoundDrawableWidth > 0 || compoundDrawableHeight > 0) {
for (Drawable drawable : drawables) {
if (drawable == null) continue;
Rect realBounds = drawable.getBounds();
float drawableWidth = realBounds.width();
if(this.compoundDrawableWidth>0)
drawableWidth = this.compoundDrawableWidth;
float drawableHeight = realBounds.height();
if(this.compoundDrawableHeight>0)
drawableHeight = this.compoundDrawableHeight;
realBounds.right = realBounds.left + Math.round(drawableWidth);
realBounds.bottom = realBounds.top + Math.round(drawableHeight);
drawable.setBounds(realBounds);
}
}
super.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]);
}
This way you can set the size of the drawable but if you care about width/height ratio make it the way suits you.
Now if you want it to automatically match height of the textview you may also override the TextView's method onSizeChanged:
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
compoundDrawableHeight = h;
resizeCompoundDrawables();
}
You my also want to declare sizes for each side, for example leftCompoundDrawableWidth, rightCompoundDrawableWidth and so on.
Note that it does not work with a Shape as drawable. Sounds like TextView only accepts it if it has the size attributes, that way one can implement it by updating the size of the shapedrawable using setSize or setIntrinsicWidth or ... Not tested.
Maybe it's worth look at ImageSpan. It's a span that replaces the text it's attached to with a Drawable that can be aligned with the bottom or with the baseline of the surrounding. I think it will automatically scale it as well based on the height of the textview.
https://developer.android.com/reference/android/text/style/ImageSpan
I Tried all the solutions but none of them worked for me, then I tried this one
in TextView
<TextView
android:gravity="left"
android:id="#+id/product_view_count"
android:text="#string/view_product_count"
android:drawableLeft="#drawable/ic_eye"
android:drawablePadding="2dp"
android:drawableTint="#color/orange"
android:textSize="20sp"
android:textColor="#color/orange"
android:textStyle="bold"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
in your Activity or fragment or Adapter. I am using my adapter like this
viewcount=itemView.findViewById(R.id.product_view_count);
holder.viewcount.setPivotX(0);
holder.viewcount.setPivotY(0);
holder.viewcount.setScaleX(.7f);
holder.viewcount.setScaleY(.7f);
by using ScaleX, ScaleY in TextView text position will change. to keep the position in left/start using setPivotX,setPivotY
Thank's to Bö macht Blau for the nice solution here
The easiest is to create a new drawable and adjust the drawable objects size
<vector xmlns:android="http://schemas.android.com/apk/res/android"
**android:width="50dp"
android:height="50dp"**
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#android:color/white">
<path
android:fillColor="#android:color/black"
android:pathData="M19,3H4.99C3.89,3 3,3.9 3,5l0.01,14c0,1.1 0.89,2 1.99,2h10l6,-6V5C21,3.9 20.1,3 19,3zM7,8h10v2H7V8zM12,14H7v-2h5V14zM14,19.5V14h5.5L14,19.5z"/>
</vector>
Related
I have an image, I want to put a TextView on a certain point(on the brown rectangle) in different devices with different screen sizes. My image is below:
CAUTION:the scaleType of the ImageView is CenterCrop
in image below I show where I want to put the TextView:
And this is my xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/startpage"<!-- my background-->
android:scaleType="centerCrop"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#fff"/>
</RelativeLayout>
There's tons of options how to do that, but seeing your pics I'd simply make my TextView aligned to top-left corner and set its layout margin to right values in dp (which I'd simply figure out in any graphics program).
There are several ways. I am quite new so someone with more knowledge would most likely have a better answer. But, you can try to align with Relative Layout. Or you can use a layout gravity to change it so that it "gravitates" towards where you want it to be.
I suggest you to start with also draw 9-patch which is a tool that helps u to select where do u want the content to fit inside the picture.
The Draw 9-patch tool is a WYSIWYG editor that allows you to create
bitmap images that automatically resize to accommodate the contents of
the view and the size of the screen.
After that you will need to check alignment and such stuff. like top left, padding-top... etc
At last, I found it myself, see these java codes:
I find the display width and height, then calculate the scale, the according to the scale I scale the margins.
#Bind(R.id.name_tv)TextView nameTV;
public final static float bgWidth = 768;
public final static float bgHeight = 1136;
public float tVsRightMargin = 123;
public float nameTVtopMargin = 314;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ResourceManager.setActivity(this);
setContentView(R.layout.main);
ButterKnife.bind(this);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int displayWidth = displayMetrics.widthPixels;
int displayHeight = displayMetrics.heightPixels;
Log.v("MainActivity","displayWidth: "+displayWidth);
Log.v("MainActivity", "displayHeight: " + displayHeight);
float scale = Math.max(displayWidth/bgWidth, displayHeight/bgHeight);
Log.v("MainActivity", "scale: "+scale);
float bgScaledWidth = scale*bgWidth;
float bgScaledHeight = scale*bgHeight;
tVsRightMargin *= scale;
nameTVtopMargin *= scale;
if(bgScaledWidth>displayWidth) {
tVsRightMargin -= ((bgScaledWidth - displayWidth) / 2f);
}
if(bgScaledHeight>displayHeight){
nameTVtopMargin -= ((bgScaledHeight-displayHeight)/2f);
}
nameTV.setText("محمد");
nameTV.setTypeface(ResourceManager.getTypeface());
Log.v("MainActivity", "top margin: " + nameTVtopMargin);
Log.v("MainActivity", "right margin: " + tVsRightMargin);
((RelativeLayout.LayoutParams) nameTV.getLayoutParams()).setMargins(0, (int) nameTVtopMargin, (int) tVsRightMargin, 0);
}
I have an imageview that looks like this
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignTop="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginBottom="80dp"
android:layout_marginTop="40dp"
android:onClick="Time"
android:adjustViewBounds="false"
android:src="#drawable/ic_launcher" />
I'm trying to get the width of the image displayed in the imageview by using
ImageView artCover = (ImageView)findViewById(R.id.imageView1);
int coverWidth = artCover.getWidth();
But the width returned is the same as the screen width and not of the image (when the image width is less then the screen width). If I do
int coverHeight = artCover.getHeight();
I get the correct height of the image. How can I get the width of the displayed image?
Your imageview's bitmap is probably scaled and aligned accordingly. You need to take this into account.
// Get rectangle of the bitmap (drawable) drawn in the imageView.
RectF bitmapRect = new RectF();
bitmapRect.right = imageView.getDrawable().getIntrinsicWidth();
bitmapRect.bottom = imageView.getDrawable().getIntrinsicHeight();
// Translate and scale the bitmapRect according to the imageview's scale-type, etc.
Matrix m = imageView.getImageMatrix();
m.mapRect(bitmapRect);
// Get the width of the image as shown on the screen:
int width = bitmapRect.width();
(note that I haven't tried to compile above code, but you'll get the gist of it :-)).
The above code only works when the ImageView has completed its layout.
You have to wait till the View tree has been measured completely which might be even later than onPostResume(). One way to deal with that is:
final ImageView artCover = (ImageView)findViewById(R.id.imageView1);
artCover.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int coverWidth = artCover.getWidth();
}
}
);
You can get image from imageview and will get width the image.
Bitmap bitmap = ((BitmapDrawable)artCover.getDrawable()).getBitmap();<p>
bitmap.getWidth();
I have this issue on my EditText and Button views, where I have a nice padding for them to space away from the text, but when I change the background with setBackgroundDrawable or setBackgroundResource that padding is lost forever.
What I found was adding a 9 patch as a background resource reset the padding - although interestingly if I added a color, or non-9 patch image, it didn't. The solution was to save the padding values before the background gets added, then set them again afterwards.
private EditText value = (EditText) findViewById(R.id.value);
int pL = value.getPaddingLeft();
int pT = value.getPaddingTop();
int pR = value.getPaddingRight();
int pB = value.getPaddingBottom();
value.setBackgroundResource(R.drawable.bkg);
value.setPadding(pL, pT, pR, pB);
I was able to wrap the element inside another layout, in this case, a FrameLayout. That enabled me to change the background on the FrameLayout without destroying the padding, which is on the contained RelativeLayout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/commentCell"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/comment_cell_bg_single" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="20dp" >
<ImageView android:id="#+id/sourcePic"
android:layout_height="75dp"
android:layout_width="75dp"
android:padding="5dp"
android:background="#drawable/photoframe"
/>
...
The other option is to set it programmatically after setting the background Drawable as suggested above. Just make sure to calculate the pixels to correct for the resolution of the device.
I had this problem in a TextView, so I subclassed TextView and made an Override method of the TextView.setBackgroundResource(int resid) method. Like this:
#Override
public void setBackgroundResource(int resid) {
int pl = getPaddingLeft();
int pt = getPaddingTop();
int pr = getPaddingRight();
int pb = getPaddingBottom();
super.setBackgroundResource(resid);
this.setPadding(pl, pt, pr, pb);
}
This way, it gets the padding of the item before it sets the resource, but doesn't actually mess with the original functionality of the method, other than keeping the padding.
Haven't tested this super thoroughly, but this method might be of use:
/**
* Sets the background for a view while preserving its current padding. If the background drawable
* has its own padding, that padding will be added to the current padding.
*
* #param view View to receive the new background.
* #param backgroundDrawable Drawable to set as new background.
*/
public static void setBackgroundAndKeepPadding(View view, Drawable backgroundDrawable) {
Rect drawablePadding = new Rect();
backgroundDrawable.getPadding(drawablePadding);
int top = view.getPaddingTop() + drawablePadding.top;
int left = view.getPaddingLeft() + drawablePadding.left;
int right = view.getPaddingRight() + drawablePadding.right;
int bottom = view.getPaddingBottom() + drawablePadding.bottom;
view.setBackgroundDrawable(backgroundDrawable);
view.setPadding(left, top, right, bottom);
}
Use this instead of view.setBackgroundDrawable(Drawable).
Just to explain what's happening :
It's actually a feature. Layout drawables you might use as backgrounds can define a padding this way :
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingRight="8dp"
>
...
</layer-list>
This padding will be set along with the new drawable background. When there's no padding, the default value is 0.
More info from an email written by Romain Guy:
https://www.mail-archive.com/android-developers#googlegroups.com/msg09595.html
Backward compatable version of cottonBallPaws's answer
/**
* Sets the background for a view while preserving its current padding. If the background drawable
* has its own padding, that padding will be added to the current padding.
*
* #param view View to receive the new background.
* #param backgroundDrawable Drawable to set as new background.
*/
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("deprecation")
public static void setBackgroundAndKeepPadding(View view, Drawable backgroundDrawable) {
Rect drawablePadding = new Rect();
backgroundDrawable.getPadding(drawablePadding);
int top = view.getPaddingTop() + drawablePadding.top;
int left = view.getPaddingLeft() + drawablePadding.left;
int right = view.getPaddingRight() + drawablePadding.right;
int bottom = view.getPaddingBottom() + drawablePadding.bottom;
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(backgroundDrawable);
} else {
view.setBackground(backgroundDrawable);
}
view.setPadding(left, top, right, bottom);
}
You can give some padding by using 9-patch images and defining the content area in the drawable.
Check this
You can also set the padding in your layout from xml or programatically
xml padding tags
android:padding
android:paddingLeft
android:paddingRight
android:paddingTop
android:paddingBottom
You can try setting the padding manually from the code after you call the setBackgroundDrawable by calling setPadding on your EditText or Button Views
For common searcher,
just add setPadding after setBackgroudDrawable. When you change your drawable, you have to call setPadding again.
Like:
view.setBackgroundDrawable(backgroundDrawable);
view.setPadding(x, x, x, x);
The cleanest way is define your paddings inside a xml-drawable which points to the drawable-image-file
Greatings
My solution was to extend the view (in my case an EditText) and override setBackgroundDrawable() and setBackgroundResource() methods:
// Stores padding to avoid padding removed on background change issue
public void storePadding(){
mPaddingLeft = getPaddingLeft();
mPaddingBottom = getPaddingTop();
mPaddingRight = getPaddingRight();
mPaddingTop = getPaddingBottom();
}
// Restores padding to avoid padding removed on background change issue
private void restorePadding() {
this.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
#Override
public void setBackgroundResource(#DrawableRes int resId) {
storePadding();
super.setBackgroundResource(resId);
restorePadding();
}
#Override
public void setBackgroundDrawable(Drawable background) {
storePadding();
super.setBackgroundDrawable(background);
restorePadding();
}
Combining the solutions of all, I wrote one in Kotlin:
fun View.setViewBackgroundWithoutResettingPadding(#DrawableRes backgroundResId: Int) {
val paddingBottom = this.paddingBottom
val paddingStart = ViewCompat.getPaddingStart(this)
val paddingEnd = ViewCompat.getPaddingEnd(this)
val paddingTop = this.paddingTop
setBackgroundResource(backgroundResId)
ViewCompat.setPaddingRelative(this, paddingStart, paddingTop, paddingEnd, paddingBottom)
}
fun View.setViewBackgroundWithoutResettingPadding(background: Drawable?) {
val paddingBottom = this.paddingBottom
val paddingStart = ViewCompat.getPaddingStart(this)
val paddingEnd = ViewCompat.getPaddingEnd(this)
val paddingTop = this.paddingTop
ViewCompat.setBackground(this, background)
ViewCompat.setPaddingRelative(this, paddingStart, paddingTop, paddingEnd, paddingBottom)
}
just change lib to v7:22.1.0 in android studio like this
compile 'com.android.support:appcompat-v7:22.1.0'
Most of answers are correct but should handle the background setting correctly.
First get the padding of your view
//Here my view has the same padding in all directions so I need to get just 1 padding
int padding = myView.getPaddingTop();
Then set the background
//If your are supporting lower OS versions make sure to verify the version
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
//getDrawable was deprecated so use ContextCompat
myView.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.bg_accent_underlined_white));
} else {
myView.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_accent_underlined_white));
}
Then set the padding the view had before the background change
myView.setPadding(padding, padding, padding, padding);
I found another solution.
I was facing the similar problem with Buttons.
Eventually, i added:
android:scaleX= "0.85"
android:scaleY= "0.85"
it worked for me. The default padding is almost the same.
In my case I had a drawable and was so stupid I didn't see the paddings were all set to 0 in the xml.
maybe it will be relevant for someone
small hack using drawable in selector doesn't remove padding
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/anything" />
</selector>
Here an improved version of cottonBallPaws' setBackgroundAndKeepPadding. This maintains the padding even if you call the method multiple times:
/**
* Sets the background for a view while preserving its current padding. If the background drawable
* has its own padding, that padding will be added to the current padding.
*/
public static void setBackgroundAndKeepPadding(View view, Drawable backgroundDrawable) {
Rect drawablePadding = new Rect();
backgroundDrawable.getPadding(drawablePadding);
// Add background padding to view padding and subtract any previous background padding
Rect prevBackgroundPadding = (Rect) view.getTag(R.id.prev_background_padding);
int left = view.getPaddingLeft() + drawablePadding.left -
(prevBackgroundPadding == null ? 0 : prevBackgroundPadding.left);
int top = view.getPaddingTop() + drawablePadding.top -
(prevBackgroundPadding == null ? 0 : prevBackgroundPadding.top);
int right = view.getPaddingRight() + drawablePadding.right -
(prevBackgroundPadding == null ? 0 : prevBackgroundPadding.right);
int bottom = view.getPaddingBottom() + drawablePadding.bottom -
(prevBackgroundPadding == null ? 0 : prevBackgroundPadding.bottom);
view.setTag(R.id.prev_background_padding, drawablePadding);
view.setBackgroundDrawable(backgroundDrawable);
view.setPadding(left, top, right, bottom);
}
You need to define a resource id via values/ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="prev_background_padding" type="id"/>
</resources>
I use this pretty easy workaround I define a accentColor in my style.xml like below
<item name="colorAccent">#0288D1</item>
and then I use the either of following styles in my Button tags
style="#style/Base.Widget.AppCompat.Button.Colored"
style="#style/Base.Widget.AppCompat.Button.Small"
for Example :
<Button
android:id="#+id/btnLink"
style="#style/Base.Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tvDescription"
android:textColor="#color/textColorPrimary"
android:text="Visit Website" />
<Button
android:id="#+id/btnSave"
style="#style/Base.Widget.AppCompat.Button.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tvDescription"
android:layout_toRightOf="#id/btnLink"
android:textColor="#color/textColorPrimaryInverse"
android:text="Save" />
How to fit an image of random size to an ImageView?
When:
Initially ImageView dimensions are 250dp * 250dp
The image's larger dimension should be scaled up/down to 250dp
The image should keep its aspect ratio
The ImageView dimensions should match scaled image's dimensions after scaling
E.g. for an image of 100*150, the image and the ImageView should be 166*250.
E.g. for an image of 150*100, the image and the ImageView should be 250*166.
If I set the bounds as
<ImageView
android:id="#+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true" />
images fit properly in the ImageView, but the ImageView is always 250dp * 250dp.
May not be answer for this specific question, but if someone is, like me, searching for answer how to fit image in ImageView with bounded size (for example, maxWidth) while preserving Aspect Ratio and then get rid of excessive space occupied by ImageView, then the simplest solution is to use the following properties in XML:
android:scaleType="centerInside"
android:adjustViewBounds="true"
(The answer was heavily modified after clarifications to the original question)
After clarifications:
This cannot be done in xml only. It is not possible to scale both the image and the ImageView so that image's one dimension would always be 250dp and the ImageView would have the same dimensions as the image.
This code scales Drawable of an ImageView to stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then the ImageView is resized to match the dimensions of the scaled image. The code is used in an activity. I tested it via button click handler.
Enjoy. :)
private void scaleImage(ImageView view) throws NoSuchElementException {
// Get bitmap from the the ImageView.
Bitmap bitmap = null;
try {
Drawable drawing = view.getDrawable();
bitmap = ((BitmapDrawable) drawing).getBitmap();
} catch (NullPointerException e) {
throw new NoSuchElementException("No drawable on given view");
} catch (ClassCastException e) {
// Check bitmap is Ion drawable
bitmap = Ion.with(view).getBitmap();
}
// Get current dimensions AND the desired bounding box
int width = 0;
try {
width = bitmap.getWidth();
} catch (NullPointerException e) {
throw new NoSuchElementException("Can't find bitmap on given view/drawable");
}
int height = bitmap.getHeight();
int bounding = dpToPx(250);
Log.i("Test", "original width = " + Integer.toString(width));
Log.i("Test", "original height = " + Integer.toString(height));
Log.i("Test", "bounding = " + Integer.toString(bounding));
// 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;
Log.i("Test", "xScale = " + Float.toString(xScale));
Log.i("Test", "yScale = " + Float.toString(yScale));
Log.i("Test", "scale = " + Float.toString(scale));
// 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);
Log.i("Test", "scaled width = " + Integer.toString(width));
Log.i("Test", "scaled height = " + Integer.toString(height));
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
Log.i("Test", "done");
}
private int dpToPx(int dp) {
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
The xml code for the ImageView:
<ImageView a:id="#+id/image_box"
a:background="#ff0000"
a:src="#drawable/star"
a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:layout_marginTop="20dp"
a:layout_gravity="center_horizontal"/>
Thanks to this discussion for the scaling code:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
UPDATE 7th, November 2012:
Added null pointer check as suggested in comments
<ImageView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
The Below code make the bitmap perfectly with same size of the imageview. Get the bitmap image height and width and then calculate the new height and width with the help of imageview's parameters. That give you required image with best aspect ratio.
int currentBitmapWidth = bitMap.getWidth();
int currentBitmapHeight = bitMap.getHeight();
int ivWidth = imageView.getWidth();
int ivHeight = imageView.getHeight();
int newWidth = ivWidth;
newHeight = (int) Math.floor((double) currentBitmapHeight *( (double) new_width / (double) currentBitmapWidth));
Bitmap newbitMap = Bitmap.createScaledBitmap(bitMap, newWidth, newHeight, true);
imageView.setImageBitmap(newbitMap)
enjoy.
try adding android:scaleType="fitXY" to your ImageView.
The Best solution that works in most cases is
Here is an example:
<ImageView android:id="#+id/avatar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
this can all be done using XML... the other methods seem pretty complicated.
Anyway, you just set the height to what ever you want in dp, then set the width to wrap content or visa versa. Use scaleType fitCenter to adjust the size of the image.
<ImageView
android:layout_height="200dp"
android:layout_width="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:src="#mipmap/ic_launcher"
android:layout_below="#+id/title"
android:layout_margin="5dip"
android:id="#+id/imageView1">
After searching for a day, I think this is the easiest solution:
imageView.getLayoutParams().width = 250;
imageView.getLayoutParams().height = 250;
imageView.setAdjustViewBounds(true);
Edited Jarno Argillanders answer:
How to fit Image with your Width and Height:
1) Initialize ImageView and set Image:
iv = (ImageView) findViewById(R.id.iv_image);
iv.setImageBitmap(image);
2) Now resize:
scaleImage(iv);
Edited scaleImage method: (you can replace EXPECTED bounding values)
private void scaleImage(ImageView view) {
Drawable drawing = view.getDrawable();
if (drawing == null) {
return;
}
Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int xBounding = ((View) view.getParent()).getWidth();//EXPECTED WIDTH
int yBounding = ((View) view.getParent()).getHeight();//EXPECTED HEIGHT
float xScale = ((float) xBounding) / width;
float yScale = ((float) yBounding) / height;
Matrix matrix = new Matrix();
matrix.postScale(xScale, yScale);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
BitmapDrawable result = new BitmapDrawable(context.getResources(), scaledBitmap);
view.setImageDrawable(result);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
And .xml:
<ImageView
android:id="#+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
if it's not working for you then replace android:background with android:src
android:src will play the major trick
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/bg_hc" />
it's working fine like a charm
Use this code:
<ImageView android:id="#+id/avatar"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
This did it for my case.
<ImageView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:scaleType="centerCrop"
android:adjustViewBounds="true" />
I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).
I was looking through this post for how to do it, and finally did what I want, not the way described here though.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/imageBackground"
android:orientation="vertical">
<ImageView
android:id="#+id/acpt_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:layout_margin="#dimen/document_editor_image_margin"
android:background="#color/imageBackground"
android:elevation="#dimen/document_image_elevation" />
and then in onCreateView method
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);
progress = view.findViewById(R.id.progress);
imageView = view.findViewById(R.id.acpt_image);
imageView.setImageBitmap( bitmap );
imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
layoutImageView()
);
return view;
}
and then layoutImageView() code
private void layoutImageView(){
float[] matrixv = new float[ 9 ];
imageView.getImageMatrix().getValues(matrixv);
int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );
imageView.setMaxHeight(h);
imageView.setMaxWidth(w);
}
And the result is that image fits inside perfectly, keeping aspect ratio,
and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.
Result
It's important ImageView to have
wrap_content and adjustViewBounds to true,
then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,
/*An optional argument to supply a maximum height for this view. Only valid if
* {#link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
* maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
* layout params to WRAP_CONTENT. */
I needed to get this done in a constraint layout with Picasso, so I munged together some of the above answers and came up with this solution (I already know the aspect ratio of the image I'm loading, so that helps):
Called in my activity code somewhere after setContentView(...)
protected void setBoxshotBackgroundImage() {
ImageView backgroundImageView = (ImageView) findViewById(R.id.background_image_view);
if(backgroundImageView != null) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = (int) Math.round(width * ImageLoader.BOXART_HEIGHT_ASPECT_RATIO);
// we adjust the height of this element, as the width is already pinned to the parent in xml
backgroundImageView.getLayoutParams().height = height;
// implement your Picasso loading code here
} else {
// fallback if no element in layout...
}
}
In my XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp">
<ImageView
android:id="#+id/background_image_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="fitStart"
app:srcCompat="#color/background"
android:adjustViewBounds="true"
tools:layout_editor_absoluteY="0dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:layout_marginRight="0dp"
android:layout_marginLeft="0dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<!-- other elements of this layout here... -->
</android.support.constraint.ConstraintLayout>
Note the lack of a constraintBottom_toBottomOf attribute. ImageLoader is my own static class for image loading util methods and constants.
I am using a very simple solution. Here my code:
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);
My pictures are added dynamically in a gridview. When you make these settings to the imageview, the picture can be automatically displayed in 1:1 ratio.
Use Simple math to resize the image . either you can resize ImageView or you can resize drawable image than set on ImageView . find the width and height of your bitmap which you want to set on ImageView and call the desired method. suppose your width 500 is greater than height than call method
//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);
You use this class for resize bitmap.
public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
public static Bitmap scaleToFitWidth(Bitmap b, int width)
{
float factor = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
}
// Scale and maintain aspect ratio given a desired height
// BitmapScaler.scaleToFitHeight(bitmap, 100);
public static Bitmap scaleToFitHeight(Bitmap b, int height)
{
float factor = height / (float) b.getHeight();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}
}
xml code is
<ImageView
android:id="#+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />
Quick answer:
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="center"
android:src="#drawable/yourImage"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Just write it in xml
android:scaleType="centerCrop"
Worked for me
In my case, I found the answer buried in a comment on this question (credit to #vida).
android:scaleType="centerInside"
How about using android:scaleType="centerInside" instead of android:scaleType="centerCrop"? It would also not crop the image but ensure that both width and height are less than or equal the imageview's width and height :) Here's a good visual guide for scaletypes: Android ImageView ScaleType: A Visual Guide
I just use ImageView inside ConstraintLayout and set adjustviewbound in ImageView to true.
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:src="#drawable/myimg"
android:adjustViewBounds="true"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
In my Android App I have a Activity which show images which have following size 244 x 330.
I want to show those images in full device width.
My layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView android:id="#+id/news_image"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginLeft="18dip"
android:layout_marginRight="18dip"
android:background="#aaaaaa" />
</LinearLayout>
</ScrollView>
I tried to set the ScaleType of the ImageView but there is no ScalingType which scales the ImageView proportional.
How can I scale the image proportionally to fit the whole screen in landscape mode AND portrait mode?
Basically what I want is something like ScaleType.CENTER_CORP but which also sets the proportional height for the image so I can see all of it and not just a part of the image.
Edit cause I know I'm confusing you with my "weird" questing.
I want to show it to you with a image.
This is what I get at the moment with my layout. I want to fill the whole grey area by scaling the image as big as needed. How can I accomplish that?
When I set the ScaleType to CENTER_CROP I get this
but this is not what I want cause you are not seeing the whole image just a part from the center.
And this is what I want it to be:
I hope this helps you to understand what I'm trying to accomplish.
Anyone knows how to do that?
Edit 2:
It might look weird and little confusing that I'm trying to display a image which is bigger in the height than the screen size but since I'm using a ScrollView in my example layout this should be ok and the user could scroll if he want to see the not displayed area.
Hope this helps to understand what I'm trying to do.
I tried really every ScaleType in my ImageView with fill_parent and wrap_content but no of them worked. I also tried everything what I found on Google but nothing worked for me either so came up with something on my own.
It was clear that the ImageView is not scaling my image like I wanted to be scaled so I had to scale it on my own. After scaling the bitmap I would set the new Bitmap as the image source to the ImageView. This works pretty good and looks very good on the G1 and on the Motorola Milestone 2.
And here is all pieces of my code
Layout:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/news_wrapper">
<ImageView android:id="#+id/news_image"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginLeft="18dip"
android:layout_marginRight="18dip"
android:background="#aaaaaa" />
</LinearLayout>
</ScrollView>
Activity
public class ScalingImages extends Activity {
private ImageView imageView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_margin);
this.imageView = (ImageView)findViewById(R.id.news_image);
// The image is coming from resource folder but it could also
// load from the internet or whatever
Drawable drawable = getResources().getDrawable(R.drawable.img);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
// Get scaling factor to fit the max possible width of the ImageView
float scalingFactor = this.getBitmapScalingFactor(bitmap);
// Create a new bitmap with the scaling factor
Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor);
// Set the bitmap as the ImageView source
this.imageView.setImageBitmap(newBitmap);
}
private float getBitmapScalingFactor(Bitmap bm) {
// Get display width from device
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
// Get margin to use it for calculating to max width of the ImageView
LinearLayout.LayoutParams layoutParams =
(LinearLayout.LayoutParams)this.imageView.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() );
}
}
Util 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 there is an better or more accurate way to accomplish the same scaling please let me know because I can't believe that such a trivial thing is so hard to accomplish.
I'm really hoping to see a better way to do this.
Thank you for reading.
the easiest way is to add android:adjustViewBounds="true" to the ImageView and set the scale type to "fitCenter"
Slightly confused on what you're looking for, exactly. If you're scaling to fit the screen, you have three options, two of which are viable if you're keeping proportions. You can use ScaleType fitCenter, which will make the image fit within the bounds proportionally, or you can use centerCrop (which you said you tried), which will stretch the shortest side of the image to fit the container (meaning some will get cropped off on the longer dimension). You can't have it stretch to fit the width AND height without either cropping, or stretching disproportionately.
EDIT: Okay, I think I get your point now. First, I'd set your LinearLayout to wrap_content for the height. Second, in code, here's one way you can do it that I can think of. There's probably also another way you could do it by first getting the screen dimensions, and then doing createScaledBitmap with the new dimensions, and then setting the background resource.
final ImageView newsImage = (ImageView)findViewById(R.id.news_image);
//get details on resolution from the display
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
//going to set what happens as the layout happens
newsImage.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int oldHeight, oldWidth, newHeight, newWidth;
//we want the new width to be as wide as the screen
newWidth = metrics.widthPixels;
oldHeight = newsImage.getDrawable().getIntrinsicHeight();
oldWidth = newsImage.getDrawable().getIntrinsicWidth();
//keeping the aspect ratio, the new height should be w1/h1 = w2/h2
newHeight = Math.floor((oldHeight * newWidth) / oldWidth);
LinearLayout.LayoutParams params =
(LinearLayout.LayoutParams)newsImage.getLayoutParams();
params.height = newHeight;
params.width = newWidth;
newsImage.setLayoutParams(params);
newsImage.setScaleType(ScaleType.CENTER);
newsImage.invalidate();
newsImage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
}
I googled everywhere and could not find a solution.
Here is what I did, that worked for me and with a scroll view.
XML file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<ImageView
android:id="#+id/manga_page_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
</ScrollView>
Have you tried setting it programmatically via ImageView.setScaleType()?
setAdjustViewBounds( false ) might help as well.
Edit: sorry, I mis-read the question. Regardless, setAdjustViewBounds() still might help. Never used it though.
I want to show those images in full
device width.
This is simple. You just have the wrong margin settings. Remove these lines and your image will show in full device width:
android:layout_marginLeft="18dip"
android:layout_marginRight="18dip"
I don't see the images anymore and the question is old but just in case someone else finds this and has the same problem. Wouldn't it be better to just get float screenWidth = getResources().getDisplayMetrics().widthPixels and set the ImageView LayoutParamters programmatically to scale the image to screenWidth. Just an idea !!
manage to achieve what I wanted, which hopefully is the same as your aim:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pgviewer);
ImageView PgContainer = (ImageView)findViewById(R.id.imageView1);
String Page = String.valueOf(getIntent().getExtras().getInt("Page"));
try {
PgContainer.setImageBitmap(getBitmapFromAsset(Page));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PgContainer.setScaleType(ScaleType.FIT_CENTER);
PgContainer.scrollTo(0, 0);
PgContainer.setScrollBarStyle(0);
}
then to scale the bitmap:
private Bitmap getBitmapFromAsset(String strName) throws IOException
{
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(strName+".png");
Bitmap bitmap = BitmapFactory.decodeStream(istr);
float screenWidth = getResources().getDisplayMetrics().widthPixels;
int ih=bitmap.getHeight();
int iw=bitmap.getWidth();
float scalefactor = screenWidth/iw;
//w = 480, h=~
//int newh = bitmap.getHeight()/bitmap.getWidth();
return android.graphics.Bitmap.createScaledBitmap(bitmap, (int)(iw*scalefactor), (int)(ih*scalefactor), true);
//return bitmap;
}
One of the ways to do it is by setting android:adjustViewBounds="true" to the ImageView and set the scale type to "fitCenter" in the xml file.
This should work as expected.
You can also do this programatically by setting ImageView.adjustViewBounds(true) and ImageView.setScaleType(ScaleType.FIT_CENTER).