Android - ImageView bottomCrop而不是centerCrop [英] Android - ImageView bottomCrop instead of centerCrop
问题描述
我正在尝试定位ImageView,以便无论ImageView的高度有多小,图像的底部始终固定在视图的底部。但是,没有任何比例类型似乎符合我的要求。 CenterCrop很接近,但我不希望图像居中。类似于CSS处理绝对定位的方式。
I'm trying to position an ImageView so that the bottom of the image is always pinned to the bottom of the view, no matter how small the height of the ImageView is. However, none of the scale types seem to fit what I am trying to do. CenterCrop is close, but I don't want the image to be centered. Similar to how CSS would handle absolute positioning.
原因是,我需要设置ImageView的高度动画,但让它看起来好像是揭示了图像的上半部分。我假设找出这种裁剪图像的方法和动画ImageView高度是最简单的方法,但如果有人知道更好的方法,我会喜欢被指向正确的方向。
The reason is, I need to animate the height of the ImageView, but make it seem as though it is "revealing" the upper portion of the image. I assume figuring out this method of cropping the image and animating the ImageView height is the easiest way to do this, but if someone knows of a better way I'd love being pointed in the right direction.
感谢任何帮助。
推荐答案
我最终继承了ImageView的子类,创建一种方法来启用BottomCrop类型图像缩放。
I ended up subclassing ImageView and creating a way to enable a 'BottomCrop' type image scaling.
我通过根据视图高度计算比例和预期图像高度,将图像分配给正确大小的RectF。
I assigned the image to a RectF of the correct size by calculating the scale and expected image height based on the view height.
public class BottomCropImage extends ImageView {
public BottomCropImage(Context context) {
super(context);
setup();
}
public BottomCropImage(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public BottomCropImage(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setup();
}
private void setup() {
setScaleType(ScaleType.MATRIX);
}
@Override
protected boolean setFrame(int l, int t, int r, int b) {
Matrix matrix = getImageMatrix();
float scale;
int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
int drawableWidth = getDrawable().getIntrinsicWidth();
int drawableHeight = getDrawable().getIntrinsicHeight();
//Get the scale
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight / (float) drawableHeight;
} else {
scale = (float) viewWidth / (float) drawableWidth;
}
//Define the rect to take image portion from
RectF drawableRect = new RectF(0, drawableHeight - (viewHeight / scale), drawableWidth, drawableHeight);
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.FILL);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
}
这篇关于Android - ImageView bottomCrop而不是centerCrop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!