sourcecode

가로 세로 비율을 유지하기 위해 ImageView에서 이미지 크기를 조정하는 방법

copyscript 2023. 6. 3. 08:38
반응형

가로 세로 비율을 유지하기 위해 ImageView에서 이미지 크기를 조정하는 방법

Android에서, 저는 다음을 정의했습니다.ImageViewlayout_width되려고fill_parent(전화기의 전체 너비를 차지함).

가 만약내붙이가미에 올린 이미지라면.ImageView는 큽니다.layout_widthAndroid가 확장할 것입니다. 그렇죠?하지만 키는 어떨까요?안드로이드가 이미지를 스케일링할 때 가로 세로 비율을 유지합니까?

제가 발견한 것은 상단과 하단에 약간의 공백이 있다는 것입니다.ImageView가 Android보다 더 큰 를 조정할 때 » » » » » »ImageView사실입니까?진짜요예? 을 없앨?만약 그렇다면, 어떻게 그 공백을 없앨 수 있습니까?

  1. 예, 기본적으로 Android는 이미지를 ImageView에 맞게 축소하여 가로 세로 비율을 유지합니다. 보기로 설정해야 android:src="..."android:background="...".src= 세로 비율을 합니다.background=에서는 이미지 크기를 조정하고 이미지를 왜곡하여 이미지 보기의 크기에 정확히 맞게 만들 수 있습니다. (그러나 배경과 소스를 동시에 사용할 수 있으며, 이는 하나의 이미지 보기만 사용하여 기본 이미지 주위에 프레임을 표시하는 데 유용할 수 있습니다.)

  2. 당은또봐합니다야한을 봐야 합니다.android:adjustViewBounds크기 조정된 이미지에 맞게 이미지 보기의 크기를 조정합니다.예를 들어 일반적으로 사각형 ImageView가 되는 사각형 이미지가 있는 경우 ViewBounds=true를 조정하면 이미지 뷰의 크기도 직사각형으로 조정됩니다.그러면 다른 보기가 이미지 보기 주위에 배치되는 방식에 영향을 미칩니다.

    그런 다음 Samuh가 썼듯이, 당신은 그것이 기본적으로 이미지의 크기를 조정하는 방법을 변경할 수 있습니다.android:scaleType하는 가장 쉬운 은 단지 입니다!그나저나, 이것이 어떻게 작동하는지를 발견하는 가장 쉬운 방법은 단지 자신이 조금만 실험하는 것이었을 것입니다.Eclipse의 미리 보기는 대개 잘못되었기 때문에 에뮬레이터 자체(또는 실제 전화기)의 레이아웃을 확인해야 합니다.

참조.

ImageView에서 그리기 가능한 가로 세로 비율을 유지하도록 경계를 조정하려면 이 값을 true로 설정합니다.

이 특정한 문제를 가진 다른 사람들에게.당신은 가지고 있습니다.ImageView이 원이하는폭의 폭을 것.fill_parent높이를 비례적으로 조정할 수 있습니다.

두을 당신의 " 두가지속추다니합가에"에 하세요.ImageView:

android:adjustViewBounds="true"
android:scaleType="centerCrop"

그리고 설정합니다.ImageView에서 지폭까지fill_parent는 높이및높이▁andwrap_content.

또한 이미지가 잘리지 않도록 하려면 다음을 수행합니다.

 android:adjustViewBounds="true"
 android:layout_centerInParent="true"

만약 당신이 원한다면,ImageView 세로 비율을 수 있도록에 이 합니다. XML에 추가합니다.

android:adjustViewBounds="true"
android:scaleType="fitCenter"

코드에 추가합니다.

// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);

이 작업을 수행하는 데 시간이 좀 걸렸지만 이미지가 화면 너비보다 작고 화면 너비보다 큰 경우 모두 작동하는 것으로 보이며 이미지를 상자에 표시하지 않습니다.

이것은 저에게 효과가 있었습니다.

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="39dip"
android:scaleType="centerCrop"
android:adjustViewBounds ="true"

제약 조건 레이아웃에서 저는 다음과 같이 작업했습니다.

<ImageView
    android:id="@+id/myImg"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"/>

그런 다음 코드에서 그리기 가능한 항목을 다음과 같이 설정합니다.

ImageView imgView = findViewById(R.id.myImg);
imgView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.image_to_show, null));

이것은 가로 세로 비율에 따라 이미지를 잘 맞추고 중심을 유지합니다.

이것은 나의 문제를 해결했습니다.

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

ImageView를 확인합니다.크기 조정 방법을 제어하고 이해하기 위한 ScaleTypeImageView가로 세로 비율을 유지하면서 이미지 크기를 조정하면 이미지의 높이 또는 너비가 다음보다 작을 수 있습니다.ImageView의 치수.

아래 코드 가로 세로 비율로 스케일 이미지 작업:

Bitmap bitmapImage = BitmapFactory.decodeFile("Your path");
int nh = (int) ( bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
your_imageview.setImageBitmap(scaled);

저는 화면보다 작은 이미지를 가지고 있습니다.최대에 비례하여 확장되고 뷰의 중심에 오도록 하려면 다음 코드를 사용해야 했습니다.

<ImageView
    android:id="@+id/my_image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    android:layout_weight="1"
    android:scaleType="fitCenter" />

그러나 상대 레이아웃이 있고 일부 요소가 ImageView 위 또는 아래로 설정되어 있으면 대부분 이미지에 의해 중복될 가능성이 높습니다.

ImageView에서 다음 속성을 사용하여 가로 세로 비율을 유지합니다.

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

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    />

이미지 품질이 감소하는 경우:

android:adjustViewBounds="true"

대신에

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

이미지를 정확하게 맞추기를 원하는 사용자는 적절한 스케일링과 잘라내기 사용 없이 이미지 보기를 사용할 수 있습니다.

imageView.setScaleType(ScaleType.FIT_XY);

여기서 imageView는 ImageView를 나타내는 뷰입니다.

화면 너비를 계산할 수 있습니다.비트맵의 크기를 조정할 수 있습니다.

 public static float getScreenWidth(Activity activity) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);
        float pxWidth = outMetrics.widthPixels;
        return pxWidth;
    }

화면 너비를 기준으로 화면 너비 및 축소 이미지 높이를 계산합니다.

float screenWidth=getScreenWidth(act)
  float newHeight = screenWidth;
  if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
     newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
  }

비트맵의 크기를 조정할 수 있습니다.

Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap, (int) screenWidth, (int) newHeight, true);

프로그래밍 방식으로 이 작업을 수행할 때는 올바른 순서로 세터를 호출해야 합니다.

imageView.setAdjustViewBounds(true)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)

이미지가 가능한 최대 공간을 차지하도록 하려면 가장 좋은 옵션은 다음과 같습니다.

android:layout_weight="1"
android:scaleType="fitCenter"

자바 코드는 필요 없습니다.다음과 같이 하면 됩니다.

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />

키는 너비 및 높이에 대한 일치 상위 항목에 있습니다.

사용자:

<ImageView
android:id="@+id/logo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/logo" />

사용해 보십시오.android:layout_gravityImageView(이미지 보기):

android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"

위의 예는 저에게 효과가 있었습니다.

가로 세로 비율을 유지하면서 컨테이너 치수에 맞게 비트맵을 조정하는 알고리즘이 있습니다.여기서 제 해결책을 찾으십시오.

이것이 누군가에게 도움이 되기를 바랍니다!

이미지 보기를 전달하고 화면 높이와 너비를 기준으로 설정할 수 있습니다.

    public void setScaleImage(EventAssetValueListenerView view){
        // Get the ImageView and its bitmap
        Drawable drawing = view.getDrawable();
        Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
        // Get current dimensions
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float xScale = ((float) 4) / width;
        float yScale = ((float) 4) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        BitmapDrawable result = new BitmapDrawable(scaledBitmap);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();

        view.setImageDrawable(result);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }

이미지 보기에 가로 세로 비율을 프로그래밍 방식으로 적용합니다.

aspectRatio = imageWidth/imageHeight   
ratioOfWidth = imageWidth/maxWidth  
ratioOfHeight = imageHeight/maxHeight  


if(ratioOfWidth > ratioOfHeight){​​​​​​​
    imageWidth = maxWidth 
    imageHeight = imageWidth/aspectRatio
}​​​​​​​ else if(ratioOfHeight > ratioOfWidth){​​​​​​​
    imageHeight = maxHeight
    imageWidth = imageHeight * aspectRatio
}​​​​​​​

그런 다음 축소된 비트맵을 사용하여 이미지 보기를 할 수 있습니다.

Bitmap scaledBitmap= Bitmap.createScaledBitmap(bitmap, (int) imageWidth , (int) imageHeight , true);

사하는경는에우용을 사용하는 .cardviewimageview그리고 고정된android:layout_height하는 데 도움이 되었습니다.Glide

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="220dp"
             xmlns:card_view="http://schemas.android.com/apk/res-auto"
             >

    <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|top"
            card_view:cardBackgroundColor="@color/colorPrimary"
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="10dp"
            card_view:cardPreventCornerOverlap="false"
            card_view:cardUseCompatPadding="true">

        <ImageView
                android:adjustViewBounds="true"
                android:maxHeight="220dp"
                android:id="@+id/iv_full"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"/>

    </android.support.v7.widget.CardView>
</FrameLayout>

이미지 크기를 축소할 수도 있습니다.당신이 다운로드하여 사용할 수 있는 도서관이 있습니다.https://github.com/niraj124124/Images-Files-scale-and-compress.git

1) compressor-v1.0. jar를 프로젝트로 가져옵니다.테스트할 아래 샘플 코드를 추가합니다.크기 조정 제한기 크기 조정 = ImageResizer.build(); 크기 조정.scale("inputImagePath", "outputImagePath", 이미지 너비, 이미지)높이);당신의 요구에 따라 더 많은 방법이 있습니다.

빠른 답변:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@drawable/yourImage"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 130, 110, false));

언급URL : https://stackoverflow.com/questions/2521959/how-to-scale-an-image-in-imageview-to-keep-the-aspect-ratio

반응형