2

I am trying to get an image from URL in Android and set it in a ImageView. What I am doing is the following:

image = new ImageView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MY_WIDTH, MY_HEIGHT);
params.leftMargin = lefMargin;
params.topMargin = topMargin;
image.setImageBitmap(BitmapFactory.decodeStream((InputStream)new URL(MY_URL).getContent());
relativeLayout.addView(image, params);

But the image does not fit my size (MY_WIDTH, MY_HEIGHT), It is showed in its own size. What to do?

Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
user1471575
  • 731
  • 2
  • 15
  • 23

3 Answers3

5

have you tried this ?

Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(MY_URL).getContent();
Bitmap bitmapScaled = Bitmap.createScaledBitmap(bitmap, MY_WIDTH, MY_HEIGHT, true);
Drawable drawable = new BitmapDrawable(bitmapScaled);
image.setBackgroundDrawable(drawable);
sunil
  • 6,444
  • 1
  • 32
  • 44
  • It doesn't if you perform it in an AsyncTask. – Maarten Nov 26 '12 at 21:23
  • This works for me, I downloaded a static map from google and after I used 'Bitmap.createScaledBitmap()'. – Alexiscanny May 24 '16 at 12:05
  • @sunil Can you show my question because I am trying to follow you answer because I want to take a favicon of saved search url but it is me leading to error this code. Here is my question. https://stackoverflow.com/questions/54233815/get-favicon-from-a-web-and-save-it-to-declared-icon-in-a-pojo-class – TheCoderGuy Jan 18 '19 at 23:26
3

add this line for ur imageview

imageview.setScaleType(ImageView.ScaleType.FIT_XY);
imageview.setAdjustViewBounds(true);
Khan
  • 7,585
  • 3
  • 27
  • 44
0

This may work try out,

image = new ImageView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MY_WIDTH, MY_HEIGHT);
params.leftMargin = lefMargin;
params.topMargin = topMargin;
image.setLayoutParams(params );
image.setImageBitmap(BitmapFactory.decodeStream((InputStream)new URL(MY_URL).getContent());
relativeLayout.addView(image);
RPB
  • 16,006
  • 16
  • 55
  • 79
  • It didn't work! I want to use a RelativeLayout, because I want to display image according to their X and Y coordinates. – user1471575 Jun 29 '12 at 06:30