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  */
16 package com.android.contacts.detail;
17 
18 import android.content.Context;
19 import android.graphics.Canvas;
20 import android.graphics.Matrix;
21 import android.util.AttributeSet;
22 import android.widget.ImageView;
23 
24 /**
25  * Extension to ImageView that handles cropping during resize animations.
26  */
27 public class TransformableImageView extends ImageView {
28 
TransformableImageView(Context context)29     public TransformableImageView(Context context) {
30         super(context);
31     }
32 
TransformableImageView(Context context, AttributeSet attrs)33     public TransformableImageView(Context context, AttributeSet attrs) {
34         super(context, attrs);
35     }
36 
TransformableImageView(Context context, AttributeSet attrs, int defStyle)37     public TransformableImageView(Context context, AttributeSet attrs, int defStyle) {
38         super(context, attrs, defStyle);
39     }
40 
41     @Override
onDraw(Canvas canvas)42     protected void onDraw(Canvas canvas) {
43         if (getDrawable() == null) {
44             return;
45         }
46         int saveCount = canvas.getSaveCount();
47         canvas.save();
48         canvas.translate(mPaddingLeft, mPaddingTop);
49         Matrix drawMatrix = new Matrix();
50         int dwidth = getDrawable().getIntrinsicWidth();
51         int dheight = getDrawable().getIntrinsicHeight();
52 
53         int vwidth = getWidth() - mPaddingLeft - mPaddingRight;
54         int vheight = getHeight() - mPaddingTop - mPaddingBottom;
55         float scale;
56         float dx = 0, dy = 0;
57 
58         if (dwidth * vheight > vwidth * dheight) {
59             scale = (float) vheight / (float) dheight;
60             dx = (vwidth - dwidth * scale) * 0.5f;
61         } else {
62             scale = (float) vwidth / (float) dwidth;
63             dy = (vheight - dheight * scale) * 0.5f;
64         }
65 
66         drawMatrix.setScale(scale, scale);
67         drawMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
68         canvas.concat(drawMatrix);
69         getDrawable().draw(canvas);
70         canvas.restoreToCount(saveCount);
71     }
72 }
73