
ある、 問題, o バグ, または彼らは単にそうしたいです。, オブジェクトに ImageView, プログラミング アンドロイド. 幅を割り当てる場合 match_parent そのオブジェクトに, 高さ wrap_content, イベントで、 イメージ あなたが登録に行く ソース いくつかあります。 高い次元 にのの、 ImageView, あるみたい 問題 いくつか.
、 問題 それは起こる ImageView オブジェクトに割り当てられているイメージが、 低い次元 そのオブジェクトに. この場合, 元のサイズの画像が表示されます。, と れない場合 ImageView 完全に.
このようなケースで, 同じくらい 再生 様々 な オプション と 属性 ImageView オブジェクト, 決して 結果を得る. プロパティを変更することができます。 scaleType, adjustViewBounds, layout_height, layout_width, … 何もないです。, 成功はありません。.
ImageView のイメージを作成する方法は完全にオブジェクトのサイズにリサイズされます。
ため 取得 目的、 イメージ の、 ImageView オブジェクトのサイズにサイズを変更します。 失うことがなく 縦横の比率, ソリューションを作成することです、 新しい Java クラス 私たちのプロジェクトを 拡張 ImageView クラスと 修正プログラム 私たちが持っている問題.
これを行うに, あなたのプロジェクトで, クレア 、 新しいクラス. Nosotros ラ バモス、llamar ResizableImageView, y su バスク es エル siguiente:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package com.mypackage; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; public class ResizableImageView extends ImageView { public ResizableImageView(Context context, AttributeSet attrs) { super(context, attrs); } public ResizableImageView(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Drawable d = getDrawable(); if (d == null) { super.setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); return; } int imageHeight = d.getIntrinsicHeight(); int imageWidth = d.getIntrinsicWidth(); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); float imageRatio = 0.0F; if (imageHeight > 0) { imageRatio = imageWidth / imageHeight; } float sizeRatio = 0.0F; if (heightSize > 0) { sizeRatio = widthSize / heightSize; } int width; int height; if (imageRatio >= sizeRatio) { width = widthSize; height = width * imageHeight / imageWidth; } else { height = heightSize; width = height * imageWidth / imageHeight; } setMeasuredDimension(width, height); } } |
一度 作成 e 実装 クラス ResizableImageView, 今は何かは、します。 変更 、 XML の、 レイアウト どこの表示が、 ImageView 我々 がこれをしたいのリサイズ画像.
仮定してみよう, 以前 変更するには, XML を変更して ImageView のとおりです。:
1 2 3 4 5 6 | <ImageView android:id="@+id/miImagen" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="https://cdn1.professor-falken.com/@drawable/imagen" /> |
まあ、ちょうどする必要があります。 変更 このようなオブジェクトのクラス、 新機能 作成されたクラス, 次の方法で:
1 2 3 4 5 6 | <com.mypackage.ResizableImageView android:id="@+id/miImagen" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="https://cdn1.professor-falken.com/@drawable/imagen" /> |
これで クラス 変化します XML コード, オブジェクト内に含まれる画像を実現します ImageView サイズを変更します。, その比例を維持します。, コンテナーより小さい 1 つのディメンションするイメージで場合でも.
