Jpoliachik's答案是不夠冷靜,讓我想概括它同時支持頂部/底部和左/右,通過可變的量。 :)現在頂部裁剪,只需撥打setOffset(0,0)
,底部裁剪setOffset(0,1)
,左邊裁剪也是setOffset(0,0)
,右邊裁剪setOffset(1,0)
。如果要在一個維度上將圖像的一部分偏移到視口中,可以調用例如setOffset(0, 0.25f)
將其向下移動25%的非可見空間,而0.5f將居中。乾杯!
public class CropImageView extends ImageView {
float mWidthPercent = 0, mHeightPercent = 0;
public CropImageView(Context context) {
super(context);
setup();
}
public CropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public CropImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup();
}
// How far right or down should we place the upper-left corner of the cropbox? [0, 1]
public void setOffset(float widthPercent, float heightPercent) {
mWidthPercent = widthPercent;
mHeightPercent = heightPercent;
}
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 = 0, drawableHeight = 0;
// Allow for setting the drawable later in code by guarding ourselves here.
if (getDrawable() != null) {
drawableWidth = getDrawable().getIntrinsicWidth();
drawableHeight = getDrawable().getIntrinsicHeight();
}
// Get the scale.
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
// Drawable is flatter than view. Scale it to fill the view height.
// A Top/Bottom crop here should be identical in this case.
scale = (float) viewHeight/(float) drawableHeight;
} else {
// Drawable is taller than view. Scale it to fill the view width.
// Left/Right crop here should be identical in this case.
scale = (float) viewWidth/(float) drawableWidth;
}
float viewToDrawableWidth = viewWidth/scale;
float viewToDrawableHeight = viewHeight/scale;
float xOffset = mWidthPercent * (drawableWidth - viewToDrawableWidth);
float yOffset = mHeightPercent * (drawableHeight - viewToDrawableHeight);
// Define the rect from which to take the image portion.
RectF drawableRect = new RectF(xOffset, yOffset, xOffset + viewToDrawableWidth,
yOffset + viewToDrawableHeight);
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
matrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.FILL);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
}
來源
2014-09-25 06:07:26
qix
如何將其轉換爲TopCropImage? – Mani
@Mani我最終做了兩個,我想它會派上用場! [Github鏈接](https://github.com/Jpoliachik/BottomTopCropImage/blob/master/example/src/com/justinpoliachik/bottomtopcropimage/TopCropImage.java) – Jpoliachik
我自己做過,因爲我需要在昨天完成它本身,感謝無論如何,我做的和你做的一樣 – Mani