android - 在imageview中拟合图像

时间:2011-09-28 09:30:57

标签: android image imageview

我正在实现一个小部件,我试图在图像视图(8mpx)中显示一个大图像,如下所示:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" android:id="@+id/widget"
    android:background="#000000"
    android:padding="15dp"
    android:layout_margin="5dp"
    android:layout_gravity="top|center_vertical|center_horizontal"


    >
<LinearLayout android:background="#ffffff" android:padding="1dp" android:layout_width="wrap_content" android:layout_weight="1"
android:layout_height="wrap_content"  >
     <ImageView 
       android:adjustViewBounds="true"
       android:id="@+id/image"
       android:src="@drawable/sample"
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_weight="1" 
       android:layout_gravity="top|center_horizontal"
       android:scaleType="fitXY"
       android:maxWidth="200dip"
       android:maxHeight="300dip"
       />
</LinearLayout>

在模拟器中,一切似乎都没问题,但是当我部署到设备时,我收到“问题加载小部件”消息。 仿真器是HVGA,我的设备分辨率为480x800。 我觉得我做错了什么?

谢谢!

=============================================== ===

根据你们的建议,我已经制作了logcat的截图。 这是:

enter image description here

4 个答案:

答案 0 :(得分:7)

imageview.setScaleType(ScaleType.CENTER_INSIDE); 

答案 1 :(得分:6)

尝试以下代码

<ImageView 
   android:adjustViewBounds="true"
   android:id="@+id/image"
   android:src="@drawable/sample"
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:layout_gravity="top|center_horizontal"
   android:scaleType="centerInside"
   />

答案 2 :(得分:2)

使用此

imageview.setImageResource(your_image);
imageview.setScaleType(ScaleType.MATRIX);       

答案 3 :(得分:2)

老帖子,但你永远不知道...

logcat显示问题:

“此过程的分配太大”

您尝试渲染的图像太大而无法放入内存中。您需要缩小图像,但不要尝试创建位图的缩放版本,否则您将遇到同样的问题。解决方案是将Bitmap加载到内存中,但仅限于它的尺寸,然后创建一个新的Bitmap,其样本大小可以减小图像的整体大小。

实际上,您甚至不需要加载图像来获得它的原始尺寸,但它通常是有意义的,因此您可以选择合适的样本大小。

e.g。

假设您的位图是从InputStream获得的:

InputStream in = ... // Your Bitmap Stream

// Decode JUST the dimensions
Options dimensionOptions = new Options();
dimensionOptions.inJustDecodeBounds = true;

BitmapFactory.decodeStream(in, null, dimensionOptions);

// Get the dimensions of the raw
int rawWidth = dimensionOptions.outWidth;

// Choose a target width for the image (screen width would make sense)
int targetWidth = 480;

// Select the sample size which best matches our target size.
// This must be an int
float sampleSize = (float)rawWidth / (float)targetWidth;

// Assume lower, which will result in a larger image
int sample = (int) FloatMath.floor(sampleSize);

// Use this to decode the original image data
Options scaleOptions = new Options();
scaleOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; // 4 bytes per pixel
scaleOptions.inSampleSize = sample;

// Now create a bitmap using the sample size
Bitmap scaled = BitmapFactory.decodeStream(in, null, scaleOptions);