Android: размер текста изменился при сочетании текста и изображения

У меня есть textView (mTextOnImage) и imageView (mImageView)
Я объединяю их, используя функцию combineImages, но когда я комбинирую, размер текста меняется.

//generate bitmap of textView by using getDrawingCache()
Bitmap bmp = Bitmap.createBitmap(mTextOnImage.getDrawingCache());

//getting image as bitmap from image view ( to use as background to combine )
BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
Bitmap bitmapBackground = drawable.getBitmap();

//combining two bitmaps
Bitmap combined = combineImages(bitmapBackground, bmp);

Это combineImages функция

 public Bitmap combineImages(Bitmap background, Bitmap foreground) {


        Bitmap cs;
        cs = Bitmap.createBitmap(background.getWidth(), background.getHeight(), Bitmap.Config.ARGB_8888);

        //creating canvas by background image's width and height
        Canvas comboImage = new Canvas(cs);
        background = Bitmap.createScaledBitmap(background, background.getWidth(), background.getHeight(), true);

        //Drawing background to canvas
        comboImage.drawBitmap(background, 0, 0, null);

        //Drawing foreground (text) to canvas            
        comboImage.drawBitmap(foreground, mTextOnImage.getLeft(),mTextOnImage.getTop(), null);

        return cs;
    }

Растровое изображение успешно объединено, но размер текста изменен.
Вот как я устанавливаю размер текста

mTextOnImage.setTextSize(getResources().getDimensionPixelSize(R.dimen.myFontSize));

В строковом ресурсе

<resources>
    <dimen name="myFontSize">40sp</dimen>
</resources>

Я получаю фоновое изображение из галереи устройства, поэтому разрешение (размер изображения) может быть другим.
Есть ли какие-то расчеты, которые я пропустил?

Кроме того, textView (mTextOnImage) можно перетаскивать, поэтому я также хочу правильно установить положение при комбинировании этих двух.

1 ответ

Решение

Было бы полезно увидеть ваш макет XML и пару изображений. В отсутствие таковых, я предлагаю вам проверить, чтобы убедиться, что ваши изображения не изменяются при отображении.

Обновление: прежде чем смотреть на более длинное решение, попробуйте изменить способ настройки размера текста. По умолчанию используется sp, а вы используете px.

mTextOnImage.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.myFontSize))

Если это не сработает, попробуйте следующее:

Я взял твой код и сделал несколько изменений, чтобы попытаться воспроизвести проблему. В макете я отображаю текстовое представление (высота и ширина = wrap_content) и изображение без изменения размера. Ниже этих двух видов я отображаю комбинированный вид. Я разместил текст комбинированного вида сверху на белом фоне, чтобы можно было быстро сравнить. Вот результат:

Два "Hello World!" Выглядят одинаково для меня. Это заставляет меня поверить, что ваш комбинированный вид изображения растягивается или сжимается, и в процессе этого ваш текст изменяется в размере, поскольку он является лишь частью изображения.

Вот мой код, который создает изображение выше. Изображение является просто "png" графикой.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private TextView mTextOnImage;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextOnImage = findViewById(R.id.textOnImage);
        mImageView = findViewById(R.id.imageView);
        mTextOnImage.post(new Runnable() {
            @Override
            public void run() {
                //generate bitmap of textView by using getDrawingCache()
                mTextOnImage.buildDrawingCache();
                Bitmap bmp = Bitmap.createBitmap(mTextOnImage.getDrawingCache());

//getting image as bitmap from image view ( to use as background to combine )
                mImageView.buildDrawingCache();
                BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
                Bitmap bitmapBackground = drawable.getBitmap();

//                Bitmap bitmapBackground = mImageView.getDrawingCache();

//combining two bitmaps
                Bitmap combined = combineImages(bitmapBackground, bmp);
                ((ImageView) findViewById(R.id.imageCombined)).setImageBitmap(combined);
            }
        });
    }

    public Bitmap combineImages(Bitmap background, Bitmap foreground) {


        Bitmap cs;
        cs = Bitmap.createBitmap(background.getWidth(), background.getHeight(), Bitmap.Config.ARGB_8888);

        //creating canvas by background image's width and height
        Canvas comboImage = new Canvas(cs);
        background = Bitmap.createScaledBitmap(background, background.getWidth(), background.getHeight(), true);

        //Drawing background to canvas
        comboImage.drawBitmap(background, 0, 0, null);

        //Drawing foreground (text) to canvas
//        comboImage.drawBitmap(foreground, mTextOnImage.getLeft(),mTextOnImage.getTop(), null);
        comboImage.drawBitmap(foreground, (mImageView.getWidth() - foreground.getWidth()) / 2,
                              0, null);

        return cs;
    }
}   

activity_main.xml

<android.support.constraint.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toTopOf="@+id/textOnImage"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed"
        app:srcCompat="@drawable/sky" />

    <TextView
        android:id="@+id/textOnImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:text="Hello World!"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="40sp"
        app:layout_constraintBottom_toTopOf="@+id/imageCombined"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <ImageView
        android:id="@+id/imageCombined"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textOnImage" />

</android.support.constraint.ConstraintLayout>
Другие вопросы по тегам