1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.contacts.detail;
17
18import android.content.Context;
19import android.graphics.Canvas;
20import android.graphics.Matrix;
21import android.util.AttributeSet;
22import android.widget.ImageView;
23
24/**
25 * Extension to ImageView that handles cropping during resize animations.
26 */
27public class TransformableImageView extends ImageView {
28
29    public TransformableImageView(Context context) {
30        super(context);
31    }
32
33    public TransformableImageView(Context context, AttributeSet attrs) {
34        super(context, attrs);
35    }
36
37    public TransformableImageView(Context context, AttributeSet attrs, int defStyle) {
38        super(context, attrs, defStyle);
39    }
40
41    @Override
42    protected void onDraw(Canvas canvas) {
43        int saveCount = canvas.getSaveCount();
44        canvas.save();
45        canvas.translate(mPaddingLeft, mPaddingTop);
46        Matrix drawMatrix = new Matrix();
47        int dwidth = getDrawable().getIntrinsicWidth();
48        int dheight = getDrawable().getIntrinsicHeight();
49
50        int vwidth = getWidth() - mPaddingLeft - mPaddingRight;
51        int vheight = getHeight() - mPaddingTop - mPaddingBottom;
52        float scale;
53        float dx = 0, dy = 0;
54
55        if (dwidth * vheight > vwidth * dheight) {
56            scale = (float) vheight / (float) dheight;
57            dx = (vwidth - dwidth * scale) * 0.5f;
58        } else {
59            scale = (float) vwidth / (float) dwidth;
60            dy = (vheight - dheight * scale) * 0.5f;
61        }
62
63        drawMatrix.setScale(scale, scale);
64        drawMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
65        canvas.concat(drawMatrix);
66        getDrawable().draw(canvas);
67        canvas.restoreToCount(saveCount);
68    }
69}
70