本文最后更新于 655 天前
// val h = (img.width * 1.0f / img.drawable.intrinsicWidth * img.drawable.intrinsicHeight).toInt()
// val animator = ValueAnimator.ofInt(img.height,h)
public class LiveImageView extends AppCompatImageView {
private int mDx;
private int mMinDx;
public LiveImageView(@NonNull Context context) {
super(context);
}
public LiveImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public LiveImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setDx(int dx) {
if (getDrawable() == null) {
return;
}
mDx = dx - mMinDx;
if (mDx <= 0) {
mDx = 0;
}
if (mDx > getDrawable().getBounds().height() - mMinDx) {
mDx = getDrawable().getBounds().height() - mMinDx;
}
invalidate();
}
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mMinDx = h;
}
public int getDx() {
return mDx;
}
@Override protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int w = getWidth();
int h = (int) (getWidth() * 1.0f / drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight());
// 图片drawable的左上角和由下角
/*
ImageView w = mathParent,h = 100
drawable.setBounds(0, 0, w, h / 2); 则最终图片显示将被压缩显示在 h / 2高度
drawable.setBounds(0, 0, w, 2h); 则最终图片显示将在2h内显示,当然超出ImageView的h部分 drawble最终的图片展示不会完全展示 2h即 仅仅部分显示-截取
*/
drawable.setBounds(0, 0, w, h);
canvas.save();
canvas.translate(0, -getDx());
super.onDraw(canvas);
canvas.restore();
}
private Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
}
// bounds实现缩放
Drawable originalDrawable = context.getDrawable(R.drawable.my_image);
int width = originalDrawable.getIntrinsicWidth();
int height = originalDrawable.getIntrinsicHeight();
int newWidth = (int) (width * scale);
int newHeight = (int) (height * scale);
originalDrawable.setBounds(0, 0, newWidth, newHeight);
originalDrawable.draw(canvas);