6

左側にテキスト付きのボタンとドローアブルがあります。アスペクト比を維持しながら、描画可能なスケールを適切なサイズ(塗りつぶしボタンの高さ)に調整する方法はありますか?

私のレイアウトからの関連する抜粋:

        <Button 
            android:text="@string/add_fav"
            android:id="@+id/event_fav_button"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:drawableLeft="@drawable/star_yellow"/>  
4

3 に答える 3

2

ボタンのサイズに基づいて画像のサイズを変更し、ボタンのサイズを取得するためのメソッドgetHeight()getWidth()メソッドを使用し、次の関数を使用してボタンの画像のサイズを変更できます。

ビットマップのサイズ変更:

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

int width = bm.getWidth();

int height = bm.getHeight();

float scaleWidth = ((float) newWidth) / width;

float scaleHeight = ((float) newHeight) / height;

// create a matrix for the manipulation

Matrix matrix = new Matrix();

// resize the bit map

matrix.postScale(scaleWidth, scaleHeight);

// recreate the new Bitmap

Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

return resizedBitmap;

}

次に、このサイズ変更された画像をボタンに使用します。 参照

于 2012-05-21T09:59:38.057 に答える
0

グラフィックでそのようなボタン(すべてを含む)を作成できますか?

または、Uはこれを試すことができます>> 1.ボタンのサイズと同じ幅と高さのレイアウト(相対または線形)を取ります。2.その中に画像ビューとテキストビューを配置します。3.レイアウトをクリック可能にします。

于 2012-05-21T09:52:21.193 に答える
0

次のコードで作成された関数を次の場所で使用できますonCreate()

    //get left drawable
    Drawable drawable = btn.getCompoundDrawables()[0];
    int imgHeight = drawable.getIntrinsicHeight();
    int imgWidth = drawable.getIntrinsicWidth();
    //for dpToPixel look here: https://stackoverflow.com/a/6327095/2306907
    float scale = (float) (dpToPixel(40)) / imgHeight;
    Rect rect = drawable.getBounds();
    int newWidth = (int)(imgWidth * scale);
    int newHeight = (int)(imgHeight * scale);
    rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); 
    rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
    rect.right = rect.left + newWidth;
    rect.bottom = rect.top + newHeight;
    drawable.setBounds(rect);

または、「普遍的な」解決策を提供しようとするこの答えを見てください。

于 2015-09-09T20:26:22.603 に答える