Imp*_*tor 4 android imageview android-layout scaletype
假设我正在从API获取一些图像。我不知道该图像的尺寸将是未来的时间,但我知道我要的是形象,成为src一个ImageView我已经设置为某个特定的大小。我希望从API获得的任何图像都可以填满整个图像ImageView,我想保留宽高比,并且不在乎某个尺寸(宽度或高度)对于视图的设置大小是否太大,因此我使用centerCrop。
<ImageView
android:layout_width="400px"
android:layout_height="300px"
android:scaleType="centerCrop" />
Run Code Online (Sandbox Code Playgroud)
如果从API返回的图像是这样的:
当将其设置为ImageView的src时,结果将类似于此(阴影部分被裁剪掉):
但是,我收到一个要求,我们应该始终显示图像的顶部并从下至上进行裁剪。因此,所需的结果是这样的:
我敢肯定这是可能的,但是我是一个网络人,不在这里工作。以ImageView某种方式扩展,还是尝试使用scaleType="matrix"and setImageMatrix(),或者是第三种未提及的选项会更好吗?
小智 5
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 Glide,您可以使用自定义转换。随意使用我的(它几乎是 Glide 的 CenterCrop 类的副本),它需要百分比:
https://gist.github.com/bjornson/3ff8888c09908d5c6cc345d0a8e1f6a7
像任何其他位图转换一样使用它:
Glide.with(getContext())
.load(imagePath)
.transform(new PositionedCropTransformation(getContext(), 1, 0))
.into(imageView);
Run Code Online (Sandbox Code Playgroud)
常用值:左上:0, 0 右上:0, 1 左下:1, 0 右下:1, 1
使用 0.5f 作为中心
| 归档时间: |
|
| 查看次数: |
4259 次 |
| 最近记录: |