1. 程式人生 > >android 按鈕的點選縮放

android 按鈕的點選縮放

1、

/**
	 * 設定點選放大效果。
	 */
	public static void setClickZoomEffect(final View view) {
		if (view != null) {
			view.setOnTouchListener(new OnTouchListener() {
				boolean cancelled;
				Rect rect = new Rect();

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						scaleTo(v, Common.MAX_CLICK_ZOOM_FACTOR);
						break;
					case MotionEvent.ACTION_MOVE:
						if (rect.isEmpty()) {
							v.getDrawingRect(rect);
						}
						if (!rect.contains((int) event.getX(), (int) event.getY())) {
							scaleTo(v, 1);
							cancelled = true;
						}
						break;
					case MotionEvent.ACTION_UP:
					case MotionEvent.ACTION_CANCEL: {
						if (!cancelled) {
							scaleTo(v, 1);
						} else {
							cancelled = false;
						}
						break;
					}
					}
					return false;
				}
			});
		}
	}

/**
	 * 對view進行縮放。
	 */
	@SuppressLint("NewApi")
	public static void scaleTo(View v, float scale) {
		if (Build.VERSION.SDK_INT >= 11) {
			v.setScaleX(scale);
			v.setScaleY(scale);
		} else {
			float oldScale = 1;
			if (v.getTag(Integer.MIN_VALUE) != null) {
				oldScale = (Float) v.getTag(Integer.MIN_VALUE);
			}
			final LayoutParams params = v.getLayoutParams();
			params.width = (int) ((params.width / oldScale) * scale);
			params.height = (int) ((params.height / oldScale) * scale);
			v.setTag(Integer.MIN_VALUE, scale);
		}
	}