gpt4 book ai didi

android - 如何像 centerCrop 那样从顶部缩放 ImageView?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:27:02 32 4
gpt4 key购买 nike

假设我从 API 获取一些图像。我事先不知道图像的尺寸是多少,但我知道我希望该图像成为我已设置为某个特定尺寸的 ImageViewsrc .我想要从 API 获得的任何图像填充整个 ImageView,我想保持宽高比,并且我不在乎某个维度(宽度或高度)是否变得对于设置大小来说太大 View - 所以我使用 centerCrop

<ImageView
android:layout_width="400px"
android:layout_height="300px"
android:scaleType="centerCrop" />

如果从API返回的图片是这样的:

Uncropped, unscaled sample image

当它被设置为 ImageView 的 src 时,结果将类似于此(阴影部分被裁掉):

Sample image scaled and cropped with centerCrop

但是,我收到一个请求,要求我们始终显示图像的顶部并从下往上裁剪。所以期望的结果是这样的:

Sample image scaled and cropped from the top

我相信这是可能的,但我是一个网络专家,在他的联盟之外运作。以某种方式扩展 ImageView 或尝试 scaleType="matrix"setImageMatrix() 或第三个未提及的选项会更好吗?

最佳答案

使用这个 TopCropImageView gist

import android.content.Context;
import android.graphics.Matrix;
import android.widget.ImageView;

/**
* ImageView to display top-crop scale of an image view.
*
* @author Chris Arriola
*/
public class TopCropImageView extends ImageView {

public TopCropImageView(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
recomputeImgMatrix();
}

@Override
protected boolean setFrame(int l, int t, int r, int b) {
recomputeImgMatrix();
return super.setFrame(l, t, r, b);
}

private void recomputeImgMatrix() {
final Matrix matrix = getImageMatrix();

float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
final int drawableWidth = getDrawable().getIntrinsicWidth();
final int drawableHeight = getDrawable().getIntrinsicHeight();

if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight / (float) drawableHeight;
} else {
scale = (float) viewWidth / (float) drawableWidth;
}

matrix.setScale(scale, scale);
setImageMatrix(matrix);
}
}

关于android - 如何像 centerCrop 那样从顶部缩放 ImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38236793/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com