Skip to content

Instantly share code, notes, and snippets.

@niusounds
Last active January 4, 2016 18:39
Show Gist options
  • Save niusounds/8662056 to your computer and use it in GitHub Desktop.
Save niusounds/8662056 to your computer and use it in GitHub Desktop.
読み込む画像の大きさに合わせてImageViewの大きさを拡大する方法。バナーを画面幅いっぱいに拡大して、その高さに合わせてImageViewの高さを調整したい場合に使えます。(Android 4.4からは scaleType="centerCrop" adjustViewBounds="true" とするだけで良いのですが)
ImageView view = new ImageView(context) {
final RectF r = new RectF();
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
if (d != null) {
r.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
getImageMatrix().mapRect(r);
setMeasuredDimension((int) r.width(), (int) r.height());
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
};
view.setScaleType(ScaleType.CENTER_CROP);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment