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 17 package com.android.launcher3.widget; 18 19 import android.content.Context; 20 import android.graphics.Bitmap; 21 import android.graphics.Canvas; 22 import android.graphics.Paint; 23 import android.graphics.Rect; 24 import android.graphics.RectF; 25 import android.util.AttributeSet; 26 import android.view.View; 27 28 /** 29 * View that draws a bitmap horizontally centered. If the image width is greater than the view 30 * width, the image is scaled down appropriately. 31 */ 32 public class WidgetImageView extends View { 33 34 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); 35 private final RectF mDstRectF = new RectF(); 36 private Bitmap mBitmap; 37 WidgetImageView(Context context)38 public WidgetImageView(Context context) { 39 super(context); 40 } 41 WidgetImageView(Context context, AttributeSet attrs)42 public WidgetImageView(Context context, AttributeSet attrs) { 43 super(context, attrs); 44 } 45 WidgetImageView(Context context, AttributeSet attrs, int defStyle)46 public WidgetImageView(Context context, AttributeSet attrs, int defStyle) { 47 super(context, attrs, defStyle); 48 } 49 setBitmap(Bitmap bitmap)50 public void setBitmap(Bitmap bitmap) { 51 mBitmap = bitmap; 52 invalidate(); 53 } 54 getBitmap()55 public Bitmap getBitmap() { 56 return mBitmap; 57 } 58 59 @Override onDraw(Canvas canvas)60 protected void onDraw(Canvas canvas) { 61 if (mBitmap != null) { 62 updateDstRectF(); 63 canvas.drawBitmap(mBitmap, null, mDstRectF, mPaint); 64 } 65 } 66 67 /** 68 * Prevents the inefficient alpha view rendering. 69 */ 70 @Override hasOverlappingRendering()71 public boolean hasOverlappingRendering() { 72 return false; 73 } 74 updateDstRectF()75 private void updateDstRectF() { 76 if (mBitmap.getWidth() > getWidth()) { 77 float scale = ((float) getWidth()) / mBitmap.getWidth(); 78 mDstRectF.set(0, 0, getWidth(), scale * mBitmap.getHeight()); 79 } else { 80 mDstRectF.set( 81 (getWidth() - mBitmap.getWidth()) * 0.5f, 82 0, 83 (getWidth() + mBitmap.getWidth()) * 0.5f, 84 mBitmap.getHeight()); 85 } 86 } 87 88 /** 89 * @return the bounds where the image was drawn. 90 */ getBitmapBounds()91 public Rect getBitmapBounds() { 92 updateDstRectF(); 93 Rect rect = new Rect(); 94 mDstRectF.round(rect); 95 return rect; 96 } 97 } 98