michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.widget; michael@0: michael@0: import android.content.Context; michael@0: import android.graphics.Canvas; michael@0: import android.graphics.Matrix; michael@0: import android.graphics.drawable.Drawable; michael@0: import android.util.AttributeSet; michael@0: import android.widget.ImageView; michael@0: michael@0: /* Special version of ImageView for thumbnails. Scales a thumbnail so that it maintains its aspect michael@0: * ratio and so that the images width and height are the same size or greater than the view size michael@0: */ michael@0: public class ThumbnailView extends ImageView { michael@0: private static final String LOGTAG = "GeckoThumbnailView"; michael@0: final private Matrix mMatrix; michael@0: private int mWidthSpec = -1; michael@0: private int mHeightSpec = -1; michael@0: private boolean mLayoutChanged; michael@0: michael@0: public ThumbnailView(Context context, AttributeSet attrs) { michael@0: super(context, attrs); michael@0: mMatrix = new Matrix(); michael@0: mLayoutChanged = true; michael@0: } michael@0: michael@0: @Override michael@0: public void onDraw(Canvas canvas) { michael@0: Drawable d = getDrawable(); michael@0: if (mLayoutChanged) { michael@0: int w1 = d.getIntrinsicWidth(); michael@0: int h1 = d.getIntrinsicHeight(); michael@0: int w2 = getWidth(); michael@0: int h2 = getHeight(); michael@0: michael@0: float scale = (w2/h2 < w1/h1) ? (float)h2/h1 : (float)w2/w1; michael@0: mMatrix.setScale(scale, scale); michael@0: } michael@0: michael@0: int saveCount = canvas.save(); michael@0: canvas.concat(mMatrix); michael@0: d.draw(canvas); michael@0: canvas.restoreToCount(saveCount); michael@0: } michael@0: michael@0: @Override michael@0: protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { michael@0: // OnLayout.changed isn't a reliable measure of whether or not the size of this view has changed michael@0: // neither is onSizeChanged called often enough. Instead, we track changes in size ourselves, and michael@0: // only invalidate this matrix if we have a new width/height spec michael@0: if (widthMeasureSpec != mWidthSpec || heightMeasureSpec != mHeightSpec) { michael@0: mWidthSpec = widthMeasureSpec; michael@0: mHeightSpec = heightMeasureSpec; michael@0: mLayoutChanged = true; michael@0: } michael@0: super.onMeasure(widthMeasureSpec, heightMeasureSpec); michael@0: } michael@0: }