我想创建一个包含两列的照片库,如图所示
必须对图像进行二次采样并保持其纵横比。这是对图像进行二次采样的自定义转换:
public ImageCustomTransformation(Context context, int maxWidth, int maxHeight) {
super(context);
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
int targetWidth, targetHeight;
double aspectRatio;
if (toTransform.getWidth() > toTransform.getHeight()) {
targetWidth = maxWidth;
aspectRatio = (double) toTransform.getHeight() / (double) toTransform.getWidth();
targetHeight = (int) (targetWidth * aspectRatio);
} else {
targetHeight = maxHeight;
aspectRatio = (double) toTransform.getWidth() / (double) toTransform.getHeight();
targetWidth = (int) (targetHeight * aspectRatio);
}
Bitmap result = Bitmap.createScaledBitmap(toTransform, targetWidth, targetHeight, false);
if (result != toTransform) {
toTransform.recycle();
}
return result;
}
这是 GridView 的代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/darker_gray">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_view_photos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/set_photo_button"
android:layout_below="@+id/relativeLayout2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:numColumns="2"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp" />
<Button
android:id="@+id/set_photo_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Upload Photo" />
</RelativeLayout>
这是 GridView 的项目:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/and`enter code here`roid"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="@android:color/white"
cardview:cardCornerRadius="5dp">
<ImageView
android:id="@+id/image_view_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"></ImageView>
</android.support.v7.widget.CardView>
为了加载我使用 Glide Library 的图像,我将上下文和维度传递给它以对图像进行子采样(转换)。结果不是我想象的那样。谁能帮我弄清楚如何从上面的示例图像中完成布局?谢谢!