Search code examples
androidscale

Scale Image to Fit in EditText


I am appending an image into an EditText and using the ImageGetter class to set the scale. At the moment I am simply using the width and height of the image as seen in ImageGetter below at

d.setBounds(0,0, d.getIntrinsicHeight(), d.getIntrinsicWidth() );

However, I would like the image set to fit the EditText width and then scale to the proper height so that the image does not appear distorted. I've researched but have yet to locate the proper methods to make this work

Appending method:

public void appendToMessageHistory(String username, String message) {
        if (username != null && message != null) {

            messageHistoryText.append(Html.fromHtml("<b>" + username + ":"
                    + "</b>" + "<br>"));
            messageHistoryText.append(Html.fromHtml(message + "<hr>" + "<br>")
                    + System.getProperty("line.separator") + "");
            messageHistoryText.append(Html.fromHtml("<img src = '" + getResources().getDrawable(R.drawable.img1) +"'/>", imageGetter, null));

        }
    }

ImageGetter:

    // To get the images you are submitting
    ImageGetter imageGetter = new ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            Drawable d = getResources().getDrawable(
                    R.drawable.img1);
            d.setBounds(0,0, d.getIntrinsicHeight(), d.getIntrinsicWidth() );
            return d;
        } 

    };

Solution

  • Why don't you try converting the Drawable to Bitmap and rescale it?

    Like,

    Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(), 
    R.drawable.img1);
    

    Then you can resize it like

    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    

    Maybe newWidth and newHeight could be the width and height of your EditText,

    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true);
    

    Then append resizedBitmap to your EditText