erdomester
erdomester

Reputation: 11829

Android set image size programmatically

How can I set the image size on a widget programmatically? I am using this code to change the image but how can I set the size?

RemoteViews updateViews = new RemoteViews(EditPreferences.this.getPackageName(), R.layout.widgetmain2);
updateViews.setImageViewBitmap(R.id.ImageView00, ((BitmapDrawable)EditPreferences.this.getResources().getDrawable(R.drawable.normal_black_op100)).getBitmap());
ComponentName thisWidget = new ComponentName(EditPreferences.this, HelloWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(EditPreferences.this);
manager.updateAppWidget(thisWidget, updateViews);

Thanks in advance

Upvotes: 1

Views: 7146

Answers (1)

Jarek Potiuk
Jarek Potiuk

Reputation: 20077

It's a very wide question in fact. There are multiple answers for it:

  1. Usually you do it in layout.xml setting appropriate layout parameters (width, height) and scaleType: http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType. This handles a lot of cases - whenever the image is set its scaling will be recalculated according to it's parameters.

  2. But sometimes you ned to do it programmatically. But it is more complex because it needs to take into account density of the screen and density of the bitmap, screen size independent pixel size and so on. There are two points here:

    • Getting bitmap in the right size. It depends whether you load bitmap from resources (it seems you do) or whether you load it manually. If you want to fully control the size of the bitmap, then you have to understand how it all works - I recommend reading http://developer.android.com/guide/practices/screens_support.html and especially the chapter Scaling Bitmap Objects created at Runtime.
    • Setting bitmap's dimensions on screen. If you want to do it on runtime and you already calculated required size in physical pixels. Remember there are also independent pixels and you need to convert physical pixels to another (look at "density independent pixels" definition and algorithms for calculation in http://developer.android.com/guide/practices/screens_support.html . Once you know the physical pixels, you can apply LayoutParameters to the ImageView. It will be something like:

Example:

LinearLayout.LayoutParams layoutParams  = new    
         LinearLayout.LayoutParams(width_physical_pixels, height_physical_pixels);
imageView.setLayoutParams(layoutParams);

IMPORTANT! LinearLayout here is just example. It should be the PARENT class of the ImageView - so layout params are always of the type of the object container rather than of the object they are set on.

Upvotes: 6

Related Questions