帮助!
我有一个奇怪的问题。我正在编写一个Android应用程序,允许用户选择要在下一页上使用的图像。这一切都很好,但是当我做的时候
imageView.setImageBitmap(bitmap);
显示新图像,但基本上垂直居中于页面上,隐藏了我在设计时放置在页面上的按钮。布局如下所示:
<?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:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/jeepfront" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="Button" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Picture resized/cropped with any buttons"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
如果我没有调用setBitmap,那么默认图片(@ drawable / jeepfront)显示就好了,在页面顶部我可以看到按钮。
有什么想法吗?我在Android上有点新手,但从1.0开始就使用Java。
谢谢, 大卫
答案 0 :(得分:1)
您可以通过实现以下代码来实现此目的。
/**
* Scales image bitmap to fit in correctly in the view. The
* {@link LayoutParams} for the view in which the bitmap to be rendered is
* set here
*
* @param bitmap
* the {@link Bitmap} object to be scaled
* @param view
* the view in which the bitmap will be rendered
* @param context
* the context being used for invoking the method dpToPx(int,
* Context)
* @return a scaled {@link Bitmap} object for the {@link View} obejct
* provided
*/
public static Bitmap scaleAssetImage(Bitmap bitmap, View view,
Context context) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int bounding = dpToPx(250, context);
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / 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);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view
.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
return scaledBitmap;
}
/**
* Converts dp to pixel
*
* @param dpValue
* the integer value to be scaled into pixels
* @param context
* the context being used for accessing resources
* @return the converted value
*/
private static int dpToPx(int dpValue, Context context) {
float density = context.getResources().getDisplayMetrics().density;
return Math.round((float) dpValue * density);
}
public static Bitmap scaleAssetImage(Bitmap bitmap, View view, Context context)
方法会接受您的bitmap
和ImageView
,并会根据LayoutParams
尺寸设置bitmap
。