Можно ли масштабировать drawableleft & drawableright в текстовом режиме?
У меня есть TextView
с drawableLeft
& drawableRight
в элементе списка.
Проблема в том, что всякий раз, когда высота TextView
больше, drawableLeft
& drawableLeft
не масштабировался автоматически в зависимости от высоты TextView
.
Можно ли масштабировать высоту drawableLeft
& drawableRight
в TextView
?
(Я использовал 9 патч изображения)
![textview drawableleft & drawableright's height problem]()
Ответы
Ответ 1
Это может помочь вам.
Существует два свойства scaleX и scaleY
Приведенный ниже код уменьшит изображение, а текст - на 30%.
Поэтому вам нужно увеличить размер шрифта с помощью большого количества "sp", так что, когда он получит размер (масштабируется), он будет соответствовать "sp", который вы предпочитаете.
Пример. Если я установил шрифт в 18, то 30% из 18 будет 5.4sp, так что грубо говоря, это значение, на которое я нацеливаюсь, потому что когда он будет масштабироваться, он станет 13sp
<TextView
android:textSize="18sp"
android:scaleX="0.7"
android:scaleY="0.7"
Последнее, что нужно сделать, это установить CompundDrawable.
tview.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.xxx), null, null, null);
Ответ 2
Я решил эквивалентную usecase, введя ScaleDrawable
и переопределяя ее .getIntrisicHeight()
, чтобы она была как минимум высотой TextView
. Часть TextView.addOnLayoutChangeListener
, необходимая для повторной привязки изменения размера Drawable
при изменении TextView
, работает с API11 +
Drawable underlyingDrawable =
new BitmapDrawable(context.getResources(), result);
// Wrap to scale up to the TextView height
final ScaleDrawable scaledLeft =
new ScaleDrawable(underlyingDrawable, Gravity.CENTER, 1F, 1F) {
// Give this drawable a height being at
// least the TextView height. It will be
// used by
// TextView.setCompoundDrawablesWithIntrinsicBounds
public int getIntrinsicHeight() {
return Math.max(super.getIntrinsicHeight(),
competitorView.getHeight());
};
};
// Set explicitly level else the default value
// (0) will prevent .draw to effectively draw
// the underlying Drawable
scaledLeft.setLevel(10000);
// Set the drawable as a component of the
// TextView
competitorView.setCompoundDrawablesWithIntrinsicBounds(
scaledLeft, null, null, null);
// If the text is changed, we need to
// re-register the Drawable to recompute the
// bounds given the new TextView height
competitorView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
competitorView.setCompoundDrawablesWithIntrinsicBounds(scaledLeft, null, null, null);
}
});
Ответ 3
Надеемся на эту помощь
Textview tv = (TextView) findViewById(R.id.tv_dummy)
int imageResource = R.mipmap.ic_image;
Drawable drawable = ContextCompat.getDrawable(context, imageResource);
int pixelDrawableSize = (int)Math.round(tv.getLineHeight() * 0.7); // Or the percentage you like (0.8, 0.9, etc.)
drawable.setBounds(0, 0, pixelDrawableSize, pixelDrawableSize); // setBounds(int left, int top, int right, int bottom), in this case, drawable is a square image
tv.setCompoundDrawables(
null, //left
null, //top
drawable, //right
null //bottom
);
Ответ 4
Единственным приемлемым ответом здесь должно быть использование ImageView с scaleTypes, как обычно. Хакерские обходные пути для масштабирования изображения в TextView, которое не поддерживается Android, кажутся... ненужными. Используйте SDK, как это было задумано.
Ответ 5
Я не нашел способ. Но вы показываете, что это список элементов. Каждый элемент будет горизонтальным LinearLayout с изображением слева направо и текстом в центре. Размер изображения имеет андроид: scaleType = "fitXY" для увеличения высоты шрифта до высоты текста.
Если вы не хотите деформировать изображение, используйте scaleType = "CENTER_INSIDE". http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
<LinearLayout
android:layout_width="fill_parent"
android:id="@+id/HeaderList"
android:layout_gravity="top"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/backImg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:background="@color/blancotransless"
android:src="@drawable/header"
android:scaleType="fitXY" >
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/NameText"
android:text="The time of prayer"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingLeft="4dp"
android:paddingTop="4dp"
/>
<ImageView
android:id="@+id/backImg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:background="@color/blancotransless"
android:src="@drawable/header"
android:scaleType="fitXY" >
</ImageView>
</LinearLayout>
Ответ 6
Просто создайте фоновый файл с 9 путями, повторяя этот шаблон.
А также, похоже, лучше будет выглядеть, если шаблон будет применен к списку, а не к отдельному элементу.
Ответ 7
Пожалуйста, попробуйте этот код. Это может вам помочь.
Drawable TextViewDrawable = context.getResources().getDrawable(imageId);
TextViewDrawable.setBounds(0, 0, TextViewDrawable.getIntrinsicWidth(),
TextViewDrawable.getIntrinsicHeight());
text_view.setCompoundDrawables(left, top, right, bottom);