现在的社交类App,聊天都是标配,此外在聊天的基础上还衍生出了很多功能,如表情包,背景,气泡等。

某一天测试给我提了一个bug,说,软键盘弹起收拢的时候聊天背景图会抖动。要解决下。我很纳闷,这块用的不是ImageView来实现的么,Android的效果是咋样,就是咋样啊。我咋知道怎么改呢?

向测试小姐姐吐槽后,小姐姐用微信聊天背景图打了我的脸😂,貌似微信的是对的。我又仔细瞅了瞅网易云信的聊天界面这块的效果,发现,恩,网易云信针对这个问题处理过了,软键盘弹起收拢,背景图不会抖。研究了几分钟,找到了关键代码。于是今天把代码抄下来,记录下。以后就不会在碰到这种问题了(⊙o⊙)…

网易云信继承重写了ImageView的部分方法:

MsgBkImageView.java

public class MsgBkImageView extends AppCompatImageView {
    public MsgBkImageView(Context context) {
        super(context);

        init();
    }

    public MsgBkImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public MsgBkImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    private final void init() {
        super.setScaleType(ScaleType.CENTER_CROP);
    }

    @Override
    public final void setScaleType(ScaleType scaleType) {
        // REJECT
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable dr = getDrawable();

        if (dr == null) {
            super.onDraw(canvas);

            return;
        }

        int dwidth = dr.getBounds().width();
        int dheight = dr.getBounds().height();

        int vwidth = getWidth() - getPaddingLeft() - getPaddingRight();
        int vheight = getHeight() - getPaddingTop() - getPaddingBottom();

        float scale;
        float dx = 0, dy = 0;

        if (dwidth * vheight > vwidth * dheight) {
            scale = (float) vheight / (float) dheight;
            dx = (vwidth - dwidth * scale) * 0.5f;
        } else {
            scale = (float) vwidth / (float) dwidth;
            dy = (vheight - dheight * scale) * 0.5f;
        }

        canvas.save();

        canvas.translate(0, -(int) (dy + 0.5f));

        super.onDraw(canvas);

        canvas.restore();
    }
}

看起来就是重写了onDraw方法,用canvas.translate方法做了处理。这个方法还没深究😂