【发布时间】:2016-07-08 18:46:12
【问题描述】:
我正在从 cms 中提取图像,它们是横幅样式(宽度 = 900,高度 = 250)。我必须在全屏肖像模式下使用它们,所以它们自然会严重失真。我用 xml 尝试了很多不同的东西,调整位图大小,毕加索变换等。但不知道此时还能尝试什么。我唯一一次能够保持质量是通过中心种植,但这不是一个选择。我需要图像保持其纵横比。这甚至可以在不牺牲纵横比的情况下做到吗?在我的 Galaxy s5 上,图像纵横比为 1.7,而所需的纵横比为 0.5625。
编辑了解更多详情:
这是一个专有项目,所以我不能包含我正在使用的图像,但它们是横幅样式。它们被用于screenSizeHeight - toolbarHeight 和screensizewidth / 1.2 的图像视图中。
这就是我尝试调整位图大小的方式。不过它只是中心裁剪,而且太大了。
public static final Bitmap scaleAndCropBitmapByPixelDimensions(final Context context, final Bitmap sourceBitmap, final int targetWidth, final int targetHeight)
{
try
{
if (context != null && sourceBitmap != null)
{
int srcWidth = sourceBitmap.getWidth();
int srcHeight = sourceBitmap.getHeight();
float targetAspectRatio = (float)targetWidth / (float)targetHeight;
float srcAspectRatio = (float)srcWidth / (float)srcHeight;
int scaleWidth = targetWidth;
int scaleHeight = targetHeight;
int x = 0;
int y = 0;
if (srcAspectRatio < targetAspectRatio)
{
scaleWidth = targetWidth;
scaleHeight = (int)((float)(1 / srcAspectRatio) * (float)scaleWidth);
x = 0;
y = (scaleHeight - targetHeight) / 2;
}
else
{
scaleHeight = targetHeight;
scaleWidth = (int)((float)srcAspectRatio * (float)scaleHeight);
x = (scaleWidth - targetWidth) / 2;
y = 0;
}
Bitmap scaledBitmap = Bitmap.createScaledBitmap(sourceBitmap, scaleWidth, scaleHeight, true);
Bitmap croppedBitmap = Bitmap.createBitmap(scaledBitmap, x, y, targetWidth, targetHeight);
return croppedBitmap;
}
}
catch (Exception ex)
{
//Log.e(LOG_TAG, "Error scaling and cropping bitmap", ex);
ex.printStackTrace();
}
return null;
}
设置位图变换
@Override
public Bitmap transform(Bitmap sourceBitmap) {
i_bitmap = Utils.scaleAndCropBitmapByPixelDimensions(mContext,sourceBitmap,targetWidth,targetHeight);
if (sourceBitmap != i_bitmap) {
// Same bitmap is returned if sizes are the same
sourceBitmap.recycle();
}
return i_bitmap;
}
图像视图 xml
<ImageView
android:id="@+id/bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="center" />
并用毕加索加载图像
Picasso.with(mContext)
.load(url)
.transform(transformation)
.into(getBg());
【问题讨论】:
标签: android bitmap imageview picasso