태그 보관물: imageview

imageview

ImageView 너비를 채우고 가로 세로 비율을 유지하도록 이미지 크기 조정

있습니다 GridView. 의 데이터 GridView는 서버의 요청입니다.

항목 레이아웃은 다음과 같습니다 GridView.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/analysis_micon_bg"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/half_activity_vertical_margin"
    android:paddingLeft="@dimen/half_activity_horizontal_margin"
    android:paddingRight="@dimen/half_activity_horizontal_margin"
    android:paddingTop="@dimen/half_activity_vertical_margin" >

    <ImageView
        android:id="@+id/ranking_prod_pic"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/app_name"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/ranking_rank_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/ranking_prod_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/ranking_prod_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

서버에서 데이터를 요청하고 이미지 URL을 가져 와서 이미지를로드합니다. Bitmap

public static Bitmap loadBitmapFromInputStream(InputStream is) {
    return BitmapFactory.decodeStream(is);
}

public static Bitmap loadBitmapFromHttpUrl(String url) {
    try {
        return loadBitmapFromInputStream((InputStream) (new URL(url).getContent()));
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return null;
    }
}

getView(int position, View convertView, ViewGroup parent)어댑터 에 메소드 코드가 있습니다.

Bitmap bitmap = BitmapUtil.loadBitmapFromHttpUrl(product.getHttpUrl());
prodImg.setImageBitmap(bitmap);

이미지 크기는 210*210입니다. Nexus 4에서 애플리케이션을 실행합니다. 이미지는 ImageView너비를 채우지 만 ImageView높이는 조정되지 않습니다. ImageView전체 이미지를 표시하지 않습니다.

이 문제를 어떻게 해결합니까?



답변

사용자 정의 클래스 또는 라이브러리를 사용하지 않는 경우 :

<ImageView
    android:id="@id/img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitCenter" />

scaleType="fitCenter" (생략시 기본값)

  • 가로 세로 비율을 유지하면서 필요에 따라 부모가 허용하는 한도에서 확대 / 축소 할 수 있습니다.

scaleType="centerInside"

  • 기본 src너비
    가 부모 너비보다 작은 경우 이미지를 가로로 가운데에 배치합니다
  • 기본 src너비
    가 부모 너비보다 큰 경우 부모 너비 가 허용하고 축소 비율을 유지하는 가로 세로 비율만큼 너비 가 넓어집니다.

사용 android:src하거나 ImageView.setImage*메소드 를 사용하는지 여부는 중요하지 않으며 키는 아마도입니다 adjustViewBounds.


답변

나는 arnefm의 대답을 좋아하지만 작은 실수를 했으므로 (댓글 참조) 수정하려고합니다.

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * ImageView that keeps aspect ratio when scaled
 */
public class ScaleImageView extends ImageView {

  public ScaleImageView(Context context) {
    super(context);
  }

  public ScaleImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public ScaleImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    try {
      Drawable drawable = getDrawable();
      if (drawable == null) {
        setMeasuredDimension(0, 0);
      } else {
        int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (measuredHeight == 0 && measuredWidth == 0) { //Height and width set to wrap_content
          setMeasuredDimension(measuredWidth, measuredHeight);
        } else if (measuredHeight == 0) { //Height set to wrap_content
          int width = measuredWidth;
          int height = width *  drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
          setMeasuredDimension(width, height);
        } else if (measuredWidth == 0){ //Width set to wrap_content
          int height = measuredHeight;
          int width = height * drawable.getIntrinsicWidth() / drawable.getIntrinsicHeight();
          setMeasuredDimension(width, height);
        } else { //Width and height are explicitly set (either to match_parent or to exact value)
          setMeasuredDimension(measuredWidth, measuredHeight);
        }
      }
    } catch (Exception e) {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
  }

}

따라서 ImageView(예를 들어) 안에 넣으면 치수가 올바르게 조정되고 치수 문제가 없습니다.ScrollView


답변

비슷한 문제가 한 번있었습니다. 커스텀 ImageView를 만들어서 해결했습니다.

public class CustomImageView extends ImageView

그런 다음 imageview의 onMeasure 메소드를 대체하십시오. 나는 내가 믿는 것과 같은 것을했다 :

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    try {
        Drawable drawable = getDrawable();

        if (drawable == null) {
            setMeasuredDimension(0, 0);
        } else {
            float imageSideRatio = (float)drawable.getIntrinsicWidth() / (float)drawable.getIntrinsicHeight();
            float viewSideRatio = (float)MeasureSpec.getSize(widthMeasureSpec) / (float)MeasureSpec.getSize(heightMeasureSpec);
            if (imageSideRatio >= viewSideRatio) {
                // Image is wider than the display (ratio)
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = (int)(width / imageSideRatio);
                setMeasuredDimension(width, height);
            } else {
                // Image is taller than the display (ratio)
                int height = MeasureSpec.getSize(heightMeasureSpec);
                int width = (int)(height * imageSideRatio);
                setMeasuredDimension(width, height);
            }
        }
    } catch (Exception e) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

가로 세로 비율을 유지하면서 이미지를 화면에 맞게 늘릴 수 있습니다.


답변

사용하십시오 android:scaleType="centerCrop".


답변

나는 위와 비슷한 것을 한 다음 내부에서 작동하지 않기 때문에 몇 시간 동안 벽에 머리를 부딪쳤다 RelativeLayout. 나는 다음 코드로 끝났다.

package com.example;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ScaledImageView extends ImageView {
    public ScaledImageView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final Drawable d = getDrawable();

        if (d != null) {
            int width;
            int height;
            if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
                height = MeasureSpec.getSize(heightMeasureSpec);
                width = (int) Math.ceil(height * (float) d.getIntrinsicWidth() / d.getIntrinsicHeight());
            } else {
                width = MeasureSpec.getSize(widthMeasureSpec);
                height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
            }
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

그리고 RelativeLayout측정 된 치수를 무시 하지 않도록하기 위해 다음과 같이했습니다 .

    <FrameLayout
        android:id="@+id/image_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/something">

        <com.example.ScaledImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="150dp"/>
    </FrameLayout>


답변

가로 세로 비율을 유지하려면 ImageView에서 다음 속성을 사용하십시오.

android:adjustViewBounds="true"
android:scaleType="fitXY"


답변

ImageView에서 이미지를 배경으로 설정하면 src (android : src)에서 설정해야합니다.

감사.