本文最后更新于 941 天前,其中的信息可能已经有所发展或是发生改变。
public class CustomImageView extends AppCompatImageView implements View.OnTouchListener {
    private float lastX, lastY;
    private int screenWidth, screenHeight;
    private int imageWidth, imageHeight;
    private float translationX, translationY;
    public CustomImageView(Context context) {
        super(context);
        init();
    }
    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    private void init() {
        setOnTouchListener(this);
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels - getStatusBarHeight() - getNavigationBarHeight();
    }
    private int getStatusBarHeight() {
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        return resourceId > 0 ? getResources().getDimensionPixelSize(resourceId) : 0;
    }
    private int getNavigationBarHeight() {
        int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        return resourceId > 0 ? getResources().getDimensionPixelSize(resourceId) : 0;
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        imageWidth = getMeasuredWidth();
        imageHeight = getMeasuredHeight();
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        float x = event.getRawX();
        float y = event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = x - lastX;
                float dy = y - lastY;
                translationX += dx;
                translationY += dy;
                // 判断图片是否超出了屏幕范围
                if (translationX < 0) {
                    translationX = 0;
                }
                if (translationY < 0) {
                    translationY = 0;
                }
                if (translationX + imageWidth > screenWidth) {
                    translationX = screenWidth - imageWidth;
                }
                if (translationY + imageHeight > screenHeight) {
                    translationY = screenHeight - imageHeight;
                }
                setTranslationX(translationX);
                setTranslationY(translationY);
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_UP:
                // 不需要做任何事情
                break;
            default:
        }
        return true;
    }
}
