SmoothImageView.java 22.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
package com.yidianling.consultant.preview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.ydl.ydlcommon.utils.StatusBarUtils;
import com.yidianling.consultant.R;


/**
 * Deprecated: 缩放图片
 ***/
public class SmoothImageView extends PhotoView {

    public enum Status {
        STATE_NORMAL,
        STATE_IN,
        STATE_OUT,
        STATE_MOVE,

    }

    private Status mStatus = Status.STATE_NORMAL;
    private static int TRANSFORM_DURATION = 400;
    private static boolean ISFUll = false;
    private static boolean ISSCALE = false;
    private Paint mPaint;
    private Matrix matrix;
    private Transform startTransform;
    private Transform endTransform;
    private Transform animTransform;
    private Rect thumbRect;
    private boolean transformStart;
    private int bitmapWidth;
    private int bitmapHeight;
    private boolean isDrag;
    ValueAnimator animator;
    private float MAX_TRANS_SCALE = 0.2f;
    private boolean isMaskPoint = false;
56
    private BasePhotoFragment.OnDragListener onDragListener;
57 58 59 60 61 62 63

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        bitmapWidth = 0;
        bitmapHeight = 0;
        thumbRect = null;
64
        onDragListener = null;
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        ISFUll = false;
        if (animator != null) {
            animator.cancel();
            animator.clone();
            animator = null;
        }
    }


    private void initSmoothImageView() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(0xFF000000);
        matrix = new Matrix();
        setScaleType(ImageView.ScaleType.FIT_CENTER);
    }

    public boolean checkMinScale() {
        if (getScale() != 1) {
            setScale(1, true);
            return false;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null) {
            return;
        }

        if (mStatus == Status.STATE_OUT || mStatus == Status.STATE_IN) {
            if (startTransform == null || endTransform == null || animTransform == null) {
                initTransform();
            }

            if (animTransform == null) {
                super.onDraw(canvas);
                return;
            }

            mPaint.setAlpha(animTransform.alpha);
            canvas.drawPaint(mPaint);
            int saveCount = canvas.getSaveCount();
            matrix.setScale(animTransform.scale, animTransform.scale);
            float translateX = -(bitmapWidth * animTransform.scale - animTransform.width) / 2;
            float translateY = -(bitmapHeight * animTransform.scale - animTransform.height) / 2;
            matrix.postTranslate(translateX, translateY);
            canvas.translate(animTransform.left, animTransform.top);
            canvas.clipRect(0, 0, animTransform.width, animTransform.height);
            canvas.concat(matrix);
            getDrawable().draw(canvas);
            canvas.restoreToCount(saveCount);

            if (transformStart) {
                startTransform();
            }
        } else if (mStatus == Status.STATE_MOVE) {
            mPaint.setAlpha(0);
            canvas.drawPaint(mPaint);
            super.onDraw(canvas);
        } else {
            mPaint.setAlpha(255);
            canvas.drawPaint(mPaint);
            super.onDraw(canvas);
        }
    }

    private int downX, downY;
    private boolean isMoved = false;
    private boolean isDownPhoto = false;
    private int alpha = 0;
    private static final int MIN_TRANS_DEST = 5;

    private void actionDown(MotionEvent event) {
        isMaskPoint = false;
        downX = (int) event.getX();
        downY = (int) event.getY();
        if (markTransform == null) {
            initTransform();
        }
        isDownPhoto = false;
        if (markTransform != null) {
            int startY = (int) markTransform.top;
            int endY = (int) (markTransform.height + markTransform.top);
            if (downY >= startY && endY >= downY) {
                isDownPhoto = true;
            }
        }
        isMoved = false;
    }

    private boolean actionMove(MotionEvent event) {
        if (!isDownPhoto && event.getPointerCount() == 1) {
            return super.dispatchTouchEvent(event);
        }
        int mx = (int) event.getX();
        int my = (int) event.getY();

        int offsetX = mx - downX;
        int offsetY = my - downY;

        // 水平方向移动不予处理
        boolean s = !isMoved && (Math.abs(offsetX) > Math.abs(offsetY) || Math.abs(offsetY) < MIN_TRANS_DEST);
        if (s) {
            return super.dispatchTouchEvent(event);
        } else {
            if (isDrag || isMaskPoint) {
                return super.dispatchTouchEvent(event);
            }
            // 一指滑动时,才对图片进行移动缩放处理
            if (event.getPointerCount() == 1) {
                mStatus = Status.STATE_MOVE;
                offsetLeftAndRight(offsetX);
                offsetTopAndBottom(offsetY);
                float scale = moveScale();
                float scaleXY = 1 - scale * 0.1f;
                setScaleY(scaleXY);
                setScaleX(scaleXY);
                isMoved = true;
                alpha = (int) (255 * (1 - scale * 0.5f));
                invalidate();
                if (alpha < 0) {
                    alpha = 0;
                }
190 191 192

                if (onDragListener != null) {
                    onDragListener.drag();
193
                }
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208
                if (alphaChangeListener != null) {
                    alphaChangeListener.onAlphaChange(alpha);
                }
                return true;
            } else {

                return super.dispatchTouchEvent(event);
            }
        }
    }

    private boolean actionCancel() {
        if (moveScale() <= MAX_TRANS_SCALE) {
            moveToOldPosition();
209 210
            if (onDragListener != null) {
                onDragListener.actionCancel();
211
            }
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        } else {
            changeTransform();
            setTag(R.id.consultant_item_image_key, true);
            if (transformOutListener != null) {
                transformOutListener.onTransformOut();
            }
        }
        return true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        if (ISSCALE) {
            if (getScale() == 1) {
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        actionDown(event);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        return actionMove(event);
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (isMoved) {
                            return actionCancel();
                        }
                        break;
                    default: {

                    }
                }
                return super.dispatchTouchEvent(event);
            } else {
                switch (action) {
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (isMoved && getScale() <= 1.0) {
                            return actionCancel();
                        }
                        break;
                    default: {
                    }
                }
                return super.dispatchTouchEvent(event);
            }
        } else {
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    actionDown(event);
                    break;
                case MotionEvent.ACTION_MOVE:
                    return actionMove(event);
                case MotionEvent.ACTION_POINTER_DOWN:
                    isMaskPoint = true;
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    if (isMoved) {
                        if (isMaskPoint) {
                            return true;
                        } else {
                            return actionCancel();
                        }
                    }
                    break;
                default: {

                }
            }
            return super.dispatchTouchEvent(event);
        }
    }

    /**
     * 未达到关闭的阈值松手时,返回到初始位置
     */
    private void moveToOldPosition() {
        ValueAnimator va = ValueAnimator.ofInt(getTop(), 0);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            int startValue = 0;

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                if (startValue != 0) {
                    offsetTopAndBottom(value - startValue);
                }
                startValue = value;
            }
        });

        ValueAnimator leftAnim = ValueAnimator.ofInt(getLeft(), 0);
        leftAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            int startValue = 0;

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                if (startValue != 0) {
                    offsetLeftAndRight(value - startValue);
                }
                startValue = value;
            }
        });

        ValueAnimator alphaAnim = ValueAnimator.ofInt(alpha, 255);
        alphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (alphaChangeListener != null) {
                    alphaChangeListener.onAlphaChange((Integer) animation.getAnimatedValue());
                }
            }
        });

        ValueAnimator scaleAnim = ValueAnimator.ofFloat(getScaleX(), 1);
        scaleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float scale = (float) animation.getAnimatedValue();
                setScaleX(scale);
                setScaleY(scale);
            }
        });

        AnimatorSet as = new AnimatorSet();
        as.setDuration(TRANSFORM_DURATION);
        as.setInterpolator(new AccelerateDecelerateInterpolator());
        as.playTogether(va, leftAnim, scaleAnim, alphaAnim);
        as.start();
    }

    private float moveScale() {
        if (markTransform == null) {
            initTransform();
        }
        return Math.abs(getTop() / markTransform.height);
    }

    private OnAlphaChangeListener alphaChangeListener;
    private OnTransformOutListener transformOutListener;

    public void setTransformOutListener(OnTransformOutListener transformOutListener) {
        this.transformOutListener = transformOutListener;
    }

    public void setAlphaChangeListener(OnAlphaChangeListener alphaChangeListener) {
        this.alphaChangeListener = alphaChangeListener;
    }

    public interface OnTransformOutListener {
        void onTransformOut();
    }

    public interface OnAlphaChangeListener {
        void onAlphaChange(int alpha);
    }

    private Transform markTransform;

    private void changeTransform() {
        if (markTransform != null) {
            Transform tempTransform = markTransform.clone();
            tempTransform.top = markTransform.top + getTop();
            tempTransform.left = markTransform.left + getLeft();
            tempTransform.alpha = alpha;
            tempTransform.scale = markTransform.scale - (1 - getScaleX()) * markTransform.scale;
            animTransform = tempTransform.clone();
            endTransform = tempTransform.clone();
        }
    }

    private void startTransform() {
        transformStart = false;
        if (animTransform == null) {
            return;
        }

        animator = new ValueAnimator();
        animator.setDuration(TRANSFORM_DURATION);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        if (mStatus == Status.STATE_IN) {
            PropertyValuesHolder scaleHolder = PropertyValuesHolder.ofFloat("animScale", startTransform.scale, endTransform.scale);
            PropertyValuesHolder alphaHolder = PropertyValuesHolder.ofInt("animAlpha", startTransform.alpha, endTransform.alpha);
            PropertyValuesHolder leftHolder = PropertyValuesHolder.ofFloat("animLeft", startTransform.left, endTransform.left);
            PropertyValuesHolder topHolder = PropertyValuesHolder.ofFloat("animTop", startTransform.top, endTransform.top);
            PropertyValuesHolder widthHolder = PropertyValuesHolder.ofFloat("animWidth", startTransform.width, endTransform.width);
            PropertyValuesHolder heightHolder = PropertyValuesHolder.ofFloat("animHeight", startTransform.height, endTransform.height);
            animator.setValues(scaleHolder, alphaHolder, leftHolder, topHolder, widthHolder, heightHolder);
        } else if (mStatus == Status.STATE_OUT) {
            PropertyValuesHolder scaleHolder = PropertyValuesHolder.ofFloat("animScale", endTransform.scale, startTransform.scale);
            PropertyValuesHolder alphaHolder = PropertyValuesHolder.ofInt("animAlpha", endTransform.alpha, startTransform.alpha);
            PropertyValuesHolder leftHolder = PropertyValuesHolder.ofFloat("animLeft", endTransform.left, startTransform.left);
            PropertyValuesHolder topHolder = PropertyValuesHolder.ofFloat("animTop", endTransform.top, startTransform.top);
            PropertyValuesHolder widthHolder = PropertyValuesHolder.ofFloat("animWidth", endTransform.width, startTransform.width);
            PropertyValuesHolder heightHolder = PropertyValuesHolder.ofFloat("animHeight", endTransform.height, startTransform.height);
            animator.setValues(scaleHolder, alphaHolder, leftHolder, topHolder, widthHolder, heightHolder);
        }
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                animTransform.alpha = (Integer) animation.getAnimatedValue("animAlpha");
                animTransform.scale = (float) animation.getAnimatedValue("animScale");
                animTransform.left = (float) animation.getAnimatedValue("animLeft");
                animTransform.top = (float) animation.getAnimatedValue("animTop");
                animTransform.width = (float) animation.getAnimatedValue("animWidth");
                animTransform.height = (float) animation.getAnimatedValue("animHeight");
                invalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                if (getTag(R.id.consultant_item_image_key) != null) {
                    setTag(R.id.consultant_item_image_key, null);
                    setOnLongClickListener(null);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                /*
                 * 如果是进入的话,当然是希望最后停留在center_crop的区域。但是如果是out的话,就不应该是center_crop的位置了
                 * , 而应该是最后变化的位置,因为当out的时候结束时,不回复视图是Normal,要不然会有一个突然闪动回去的bug
                 */
                if (onTransformListener != null) {
                    onTransformListener.onTransformCompleted(mStatus);
                }
                if (mStatus == Status.STATE_IN) {
                    mStatus = Status.STATE_NORMAL;
                }
            }
        });
        animator.start();

    }

    public void transformIn(onTransformListener listener) {
        setOnTransformListener(listener);
        transformStart = true;
        mStatus = Status.STATE_IN;
        invalidate();
    }

    public void transformOut(onTransformListener listener) {
        if (getTop() != 0) {
            offsetTopAndBottom(-getTop());
        }
        if (getLeft() != 0) {
            offsetLeftAndRight(-getLeft());
        }
        if (getScaleX() != 1) {
            setScaleX(1);
            setScaleY(1);
        }
        setOnTransformListener(listener);
        transformStart = true;
        mStatus = Status.STATE_OUT;
        invalidate();
    }

    /**
     * 设置起始位置图片的Rect
     * g
     *
     * @param thumbRect 参数
     */
    public void setThumbRect(Rect thumbRect) {
        this.thumbRect = thumbRect;
    }

485 486
    public void setOnDragListener(BasePhotoFragment.OnDragListener dragListener) {
        this.onDragListener = dragListener;
487 488
    }

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    private void initTransform() {
        if (getDrawable() == null) {
            return;
        }
        if (startTransform != null && endTransform != null && animTransform != null) {
            return;
        }
        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        if (getDrawable() instanceof BitmapDrawable) {
            Bitmap mBitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            bitmapWidth = mBitmap.getWidth();
            bitmapHeight = mBitmap.getHeight();
        } else if (getDrawable() instanceof ColorDrawable) {
            ColorDrawable colorDrawable = (ColorDrawable) getDrawable();
            bitmapWidth = colorDrawable.getIntrinsicWidth();
            bitmapHeight = colorDrawable.getIntrinsicHeight();
        } else {
            Bitmap mBitmap = Bitmap.createBitmap(getDrawable().getIntrinsicWidth(),
                    getDrawable().getIntrinsicHeight(), Bitmap.Config.RGB_565);
            bitmapWidth = mBitmap.getWidth();
            bitmapHeight = mBitmap.getHeight();
        }
        startTransform = new Transform();
        startTransform.alpha = 0;
        if (thumbRect == null) {
            thumbRect = new Rect();
        }

        startTransform.left = thumbRect.left;
        if (ISFUll) {
            startTransform.top = thumbRect.top;
        } else {

            startTransform.top = thumbRect.top - StatusBarUtils.Companion.getStatusBarHeight(getContext().getApplicationContext());
        }
        startTransform.width = thumbRect.width();
        startTransform.height = thumbRect.height();
        //开始时以CenterCrop方式显示,缩放图片使图片的一边等于起始区域的一边,另一边大于起始区域
        float startScaleX = (float) thumbRect.width() / bitmapWidth;
        float startScaleY = (float) thumbRect.height() / bitmapHeight;
        startTransform.scale = startScaleX > startScaleY ? startScaleX : startScaleY;

        //结束时以fitCenter方式显示,缩放图片使图片的一边等于View的一边,另一边大于View
        float endScaleX = (float) getWidth() / bitmapWidth;
        float endScaleY = (float) getHeight() / bitmapHeight;
        endTransform = new Transform();
        endTransform.scale = endScaleX < endScaleY ? endScaleX : endScaleY;
        endTransform.alpha = 255;
        int endBitmapWidth = (int) (endTransform.scale * bitmapWidth);
        int endBitmapHeight = (int) (endTransform.scale * bitmapHeight);
        endTransform.left = (getWidth() - endBitmapWidth) / 2;
        endTransform.top = (getHeight() - endBitmapHeight) / 2;
        endTransform.width = endBitmapWidth;
        endTransform.height = endBitmapHeight;

        if (mStatus == Status.STATE_IN) {
            animTransform = startTransform.clone();
        } else if (mStatus == Status.STATE_OUT) {
            animTransform = endTransform.clone();
        }
        markTransform = endTransform;
    }

    private onTransformListener onTransformListener;

    public void setOnTransformListener(SmoothImageView.onTransformListener onTransformListener) {
        this.onTransformListener = onTransformListener;
    }

    public interface onTransformListener {
        void onTransformCompleted(Status status);

    }

    private class Transform implements Cloneable {
        float left, top, width, height;
        int alpha;
        float scale;

        @Override
        public Transform clone() {
            Transform obj = null;
            try {
                obj = (Transform) super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return obj;
        }
    }

    public SmoothImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSmoothImageView();
    }

    public SmoothImageView(Context context) {
        super(context);
        initSmoothImageView();
    }

    /***
     * 设置图片拖拽返回
     * @param isDrag  true  可以 false 默认 true
     * **/
    public void setDrag(boolean isDrag, float sensitivity) {
        this.isDrag = isDrag;
        this.MAX_TRANS_SCALE = sensitivity;
    }

    /***
     *  设置动画的时长
     * @param duration  单位毫秒
     * **/
    public static void setDuration(int duration) {
        TRANSFORM_DURATION = duration;
    }

    /***
     *   获取动画的时长
     * **/
    public static int getDuration() {
        return TRANSFORM_DURATION;
    }

    /***
     *  设置是否全屏
     * @param isFull true 全屏
     * **/
    public static void setFullscreen(boolean isFull) {
        ISFUll = isFull;
    }

    /***
     *  设置只有图片没有放大或者的缩小状态触退出
     * @param isScale    true false
     * **/
    public static void setIsScale(boolean isScale) {
        ISSCALE = isScale;
    }
}