Подтвердить что ты не робот

Получить отображаемый размер изображения внутри ImageView

Код прост:

<ImageView android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:src="@drawable/cat"/>

Обратите внимание, что ImageView использовал fill_parent для ширины и высоты.

Изображение cat представляет собой небольшое изображение, и оно будет увеличено, чтобы соответствовать ImageView, и одновременно поддерживать соотношение ширины и высоты.

Мой вопрос в том, как получить отображаемый размер изображения? Я пробовал:

imageView.getDrawable().getIntrinsicHeight()

Но какая из них оригинальная высота изображения cat.

Я пробовал:

imageView.getDrawable().getBounds()

Но возвращает Rect(0,0,0,0).

4b9b3361

Ответ 1

будет работать следующее:

ih=imageView.getMeasuredHeight();//height of imageView
iw=imageView.getMeasuredWidth();//width of imageView
iH=imageView.getDrawable().getIntrinsicHeight();//original height of underlying image
iW=imageView.getDrawable().getIntrinsicWidth();//original width of underlying image

if (ih/iH<=iw/iW) iw=iW*ih/iH;//rescaled width of image within ImageView
else ih= iH*iw/iW;//rescaled height of image within ImageView

(iw x ih) теперь представляет фактическое масштабируемое (ширина x высота) для изображения в представлении (другими словами, отображаемый размер изображения)


EDIT: Я думаю, что лучше написать вышеупомянутый ответ (и тот, который работает с ints):

            final int actualHeight, actualWidth;
            final int imageViewHeight = imageView.getHeight(), imageViewWidth = imageView.getWidth();
            final int bitmapHeight = ..., bitmapWidth = ...;
            if (imageViewHeight * bitmapWidth <= imageViewWidth * bitmapHeight) {
                actualWidth = bitmapWidth * imageViewHeight / bitmapHeight;
                actualHeight = imageViewHeight;
            } else {
                actualHeight = bitmapHeight * imageViewWidth / bitmapWidth;
                actualWidth = imageViewWidth;
            }

            return new Point(actualWidth,actualHeight);

Ответ 2

Вот вспомогательная функция для получения границ изображения в imageView.

/**
 * Helper method to get the bounds of image inside the imageView.
 *
 * @param imageView the imageView.
 * @return bounding rectangle of the image.
 */
public static RectF getImageBounds(ImageView imageView) {
    RectF bounds = new RectF();
    Drawable drawable = imageView.getDrawable();
    if (drawable != null) {
        imageView.getImageMatrix().mapRect(bounds, new RectF(drawable.getBounds()));
    }
    return bounds;
}

Ответ 3

Я думаю, что многие люди приходят из этого примера https://developer.android.com/training/animation/zoom.html и не хотят использовать android:scaleType="centerCrop" (возможно, потому что ImageView находится в макете ограничения, и вы хотите увидеть маленькое изображение без обрезки), не волнуйтесь, Я получил твою спину!

Просто замените весь блок, начиная с

// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the "center crop" technique.

со следующим

//adjust for scaled image to constraint
int realheight = ResourcesCompat.getDrawable(getResources(),imageResId,null).getIntrinsicHeight();
int realwidth = ResourcesCompat.getDrawable(getResources(),imageResId,null).getIntrinsicWidth();

// Adjust the start bounds to be the same aspect ratio as the final
// bounds using ueen adjusteddimensions technique. This prevents undesirable
// stretching during the animation. Also calculate the start scaling
// factor (the end scaling factor is always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height()
        > (float) startBounds.width() / startBounds.height()) {
    // Extend start bounds horizontally
    // after check whether height or width needs adjusting
    if ((float) startBounds.width() / startBounds.height() < (float) realwidth / realheight) {
        int adjustedheight = realheight*startBounds.width()/realwidth;
        int adjustedoffset = (startBounds.height()-adjustedheight) / 2;
        startScale = (float) adjustedheight / finalBounds.height();
        float startWidth = startScale * finalBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
        startBounds.offset(+0, +adjustedoffset);
    } else {
        int adjustedwidth = realwidth*startBounds.height()/realheight;
        int adjustedoffset = (startBounds.width()-adjustedwidth) / 2;
        startScale = (float) startBounds.height() / finalBounds.height();
        float startWidth = startScale * finalBounds.width();
        float deltaWidth = (startWidth - adjustedwidth) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
        startBounds.offset(+adjustedoffset, +0);
    }
} else {
    // Extend start bounds vertically
    // after check whether height or width needs adjusting
    if ((float) startBounds.width() / startBounds.height() > (float) realwidth / realheight) {
        int adjustedwidth = realwidth*startBounds.height()/realheight;
        int adjustedoffset = (startBounds.width()-adjustedwidth) / 2;
        startScale = (float) adjustedwidth / finalBounds.width();
        float startHeight = startScale * finalBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
        startBounds.offset(+adjustedoffset, +0);
    } else {
        int adjustedheight = realheight*startBounds.width()/realwidth;
        int adjustedoffset = (startBounds.height()-adjustedheight) / 2;
        startScale = (float) startBounds.width() / finalBounds.width();
        float startHeight = startScale * finalBounds.height();
        float deltaHeight = (startHeight - adjustedheight) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
        startBounds.offset(+0, +adjustedoffset);
    }
}

работает как шарм, милости просим :)

Дальнейшее объяснение: как обычно, мы проверяем, выше ли изображение, чем ширина (расширенная высота изображения должна соответствовать высоте extendedImageView) или наоборот. Затем мы проверяем, соответствует ли изображение в исходном (меньшем) ImageView (thumbView) ширине или высоте, чтобы мы могли отрегулировать пространство. Таким образом, мы достигаем плавного масштабирования анимации, не обрезая изображение в thumbView, независимо от его размера (так как они могут меняться от устройства к устройству при использовании констант) или изображения.

Ответ 4

использовать

// For getting imageview height
imgObj.getMeasuredHeight()


// For getting imageview width
imgObj.getMeasuredWidth();


//For getting image height inside ImageView
 imgObj.getDrawable().getIntrinsicHeight();


//For getting image width inside ImageView
 imgObj.getDrawable().getIntrinsicWidth();