Development Tip

Android ImageView : 너비 맞추기

yourdevel 2020. 11. 25. 21:17
반응형

Android ImageView : 너비 맞추기


나는 이미지를 다운로드하고을 사용하여 동적으로 화면 배경으로 설정합니다 Imageview. 나는 ScaleType이미지의 크기를 조정 하려고 시도했습니다 .

이미지 높이가 폭 다음보다 큰 경우 ScaleTypes fitStart, fitEnd그리고 fitCenter일을하지 않습니다. Android는 사진의 크기를 줄이고 높이를 기준으로 맞추지 만 너비의 일부로 여분의 빈 공간이 있습니다.

너비를 기준으로 사진을 축소하여 너비에 맞도록하고 싶습니다. 높이의 일부로 여분의 빈 공간이 있거나 높이가 너무 길어도보기에서 벗어나도 괜찮습니다. (가능하다면?).

ScaleType.XY사진의 크기를 조정하고 모든 것을에 맞 춥니 다 ImageView. 이미지 높이 / 무게 비율은 신경 쓰지 않습니다.

<ImageView 
                android:id="@+id/background"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:adjustViewBounds="true"
                android:scaleType="fitStart"
            />

이 코드를 사용하여 끝났습니다.

<ImageView 
                android:id="@+id/background"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:src="@drawable/name"
            />

src대신을 사용하여 이미지를 설정했는지 확인하십시오 background.


android:adjustViewBounds="true" 일을한다!


여기 에서 찾은이 우아한 솔루션 은 당신에게 매력처럼 작동 할 것입니다.

기본적으로 확장하는 작은 클래스를 만들고 원하는대로 너비와 높이를 조정하기 위해 메서드를 ImageView재정의하기 만하면 onMeasure됩니다. 여기에서는 다음을 사용하여 너비에 맞게 조정합니다.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
    setMeasuredDimension(width, height);
}

이 특수 기능을 다음 ImageView과 같이 사용합니다.

<your.activity.package.AspectRatioImageView 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_vertical"
    android:src="@drawable/test" />

단순히 화면의 너비를 채우고 높이에 비례하고 이미지의 비율을 알고 싶다면 OnCreate ()에서이 작업을 수행 할 수있는 간단한 방법이 있습니다.

setContentView(R.layout.truppview_activity);
trupImage = (ImageView) findViewById(R.id.trupImage);

Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float scWidth = outMetrics.widthPixels;
trupImage.getLayoutParams().width = (int) scWidth;
trupImage.getLayoutParams().height = (int) (scWidth * 0.6f);

0.6은 비율 조정입니다 (물론 이미지의 w & h를 알고 있다면 자동으로 계산할 수도 있습니다).

추신 :
다음은 XML 측면입니다.

  <ImageView
        android:id="@+id/trupImage"
        android:layout_width="match_parent"
        android:background="@color/orange"
        android:layout_height="match_parent" 
        android:adjustViewBounds="true" 
        android:scaleType="fitCenter" />

이것은 나를 위해 작동합니다.

ImageView를 확장하는 클래스 만들기

    package com.yourdomain.utils;

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

    public class ResizableImageView extends ImageView {

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

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

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

In xml use the following instead of ImageView

    <com.yourdomain.utils.ResizableImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/test" />

I think you cant do it only with XML, you need to resize yourself, the bitmap

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();

        try {
            ((ImageView) findViewById(R.id.background))
                    .setImageBitmap(ShrinkBitmap(width));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

then

private Bitmap ShrinkBitmap(int width)
        throws FileNotFoundException {

    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.img, bmpFactoryOptions);
    int widthRatio = (int) android.util.FloatMath
            .ceil(bmpFactoryOptions.outWidth / (float) width);


    bmpFactoryOptions.inSampleSize = widthRatio;



    if (bmpFactoryOptions.inSampleSize <= 0)
        bmpFactoryOptions.inSampleSize = 0;
    bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    bmpFactoryOptions.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeResource(getResources(),
            R.drawable.img, bmpFactoryOptions);
    return bitmap;

}

And the layout

 <ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/background"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
  />

참고URL : https://stackoverflow.com/questions/12059328/android-imageview-fit-width

반응형