source

ImageView - 높이와 일치하는 너비가 있습니까?

ittop 2023. 9. 24. 13:06
반응형

ImageView - 높이와 일치하는 너비가 있습니까?

저는 이미지 뷰를 가지고 있습니다.저는 그것의 너비를 fill_parent로 하고 싶습니다.너비가 어떻게 되든 높이가 되었으면 합니다.예를 들어,

<ImageView
  android:layout_width="fill_parent"
  android:layout_height="whatever the width ends up being" />

나만의 뷰 클래스를 만들지 않아도 레이아웃 파일에서 그런 것이 가능합니까?

감사해요.

지원 라이브러리 대신 AndroidX를 사용하도록 2021년 7월 28일 업데이트

먼저 프로젝트에 AndroidX를 가져오는지 확인하고 여기에 있는 지침을 따릅니다.

그럼 당신의 이미지를 a안에 싸세요.ConstraintLayout, 해당 분야는 다음과 같습니다.

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />

</androidx.constraintlayout.widget.ConstraintLayout>

여기를 보시오

아마도 이것이 당신의 질문에 대답해 줄 것입니다.

<ImageView
    android:id="@+id/cover_image"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true" />

당신은 무시할 수 있습니다.scaleType이 특정 상황에 대한 속성입니다.

이렇게 하려면 LayoutParams(레이아웃 매개변수)를 사용하여 실행 시 뷰 폭을 알고 나면 뷰 높이를 동적으로 설정할 수 있습니다.실행 시 뷰 너비를 얻으려면 실행 가능 스레드를 사용해야 합니다. 그렇지 않으면 레이아웃이 아직 그려지지 않았기 때문에 뷰 너비를 알기 전에 높이를 설정하려고 할 것입니다.

문제 해결 방법의 예:

final FrameLayout mFrame = (FrameLayout) findViewById(R.id.frame_id);

    mFrame.post(new Runnable() {

        @Override
        public void run() {
            RelativeLayout.LayoutParams mParams;
            mParams = (RelativeLayout.LayoutParams) mFrame.getLayoutParams();
            mParams.height = mFrame.getWidth();
            mFrame.setLayoutParams(mParams);
            mFrame.postInvalidate();
        }
    });

레이아웃 매개변수는 보기가 있는 상위 보기 유형이어야 합니다.내 FrameLayout은 xml 파일의 RelativeLayout 안에 있습니다.

    mFrame.postInvalidate();

UI 스레드가 아닌 별도의 스레드에 있는 동안 보기를 강제로 다시 그리기 위해 호출됩니다.

RecycleerView 항목에 대한 David Chu의 답변을 얻을 수 없었고 ImageView를 부모에게 제한해야 한다는 것을 알게 되었습니다.ImageView 너비를 다음으로 설정합니다.0dp시작과 끝을 부모에게 제한합니다.너비를 다음으로 설정할지 잘 모르겠습니다.wrap_content아니면match_parent경우에 따라 효과가 있지만 제약 조건 레이아웃의 자식이 부모를 채우도록 하는 것이 더 나은 방법이라고 생각합니다.

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="1:1"/>

</androidx.constraintlayout.widget.ConstraintLayout>

영상 뷰가 제약 조건 레이아웃 내에 있는 경우 다음 제약 조건을 사용하여 사각 영상 뷰를 만들 수 있습니다. 반드시 1:1을 사용하여 사각 영상 뷰를 만듭니다.

<ImageView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:id="@+id/ivImageView"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

여기서 제가 한 일은 항상 높이와 같은 폭을 가진 이미지 버튼(한 방향의 멍청한 빈 여백을 피함)을 갖기 위해 한 일입니다.SDK의 버그로 간주됩니다.

ImageButton에서 확장되는 SquareImageButton 클래스를 정의했습니다.

package com.myproject;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageButton;

    public class SquareImageButton extends ImageButton {

        public SquareImageButton(Context context) {
        super(context);


        // TODO Auto-generated constructor stub
    }

    public SquareImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub

    }

    public SquareImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub

    }

    int squareDim = 1000000000;

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);


        int h = this.getMeasuredHeight();
        int w = this.getMeasuredWidth();
        int curSquareDim = Math.min(w, h);
        // Inside a viewholder or other grid element,
        // with dynamically added content that is not in the XML,
        // height may be 0.
        // In that case, use the other dimension.
        if (curSquareDim == 0)
            curSquareDim = Math.max(w, h);

        if(curSquareDim < squareDim)
        {
            squareDim = curSquareDim;
        }

        Log.d("MyApp", "h "+h+"w "+w+"squareDim "+squareDim);


        setMeasuredDimension(squareDim, squareDim);

    }

}

여기 제 xml이 있습니다.

<com.myproject.SquareImageButton
            android:id="@+id/speakButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:scaleType="centerInside"
            android:src="@drawable/icon_rounded_no_shadow_144px"
            android:background="#00ff00"
            android:layout_alignTop="@+id/searchEditText"
            android:layout_alignBottom="@+id/searchEditText"
            android:layout_alignParentLeft="true"
           />

매력적으로 작동합니다!

레이아웃만 가지고는 할 수 없어요, 제가 해봤어요.제가 아주 간단한 수업을 작성하게 되었는데, github에서 확인하실 수 있습니다.SquareImage.java 대규모 프로젝트의 일부이지만 약간의 복사 및 붙여넣기를 통해 수정할 수 있는 것은 없습니다(Apache 2.0에 따라 라이센스가 부여됨).

기본적으로 높이/폭을 다른 차원과 동일하게 설정하면 됩니다(스케일링을 원하는 방식에 따라).

: 를 수 .scaleType속성이지만 뷰의 경계가 가시적인 이미지를 넘어 확장되므로 뷰 근처에 다른 뷰를 배치하는 경우 문제가 됩니다.

Android에서는 26.0.0% 상대 배치가 더 이상 사용되지 않습니다.

이 문제를 해결하는 가장 좋은 방법은 다음과 같습니다.

<android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

    <ImageView android:layout_width="match_parent"
               android:layout_height="0dp"
               android:scaleType="centerCrop"
               android:src="@drawable/you_image"                       
               app:layout_constraintDimensionRatio="1:1"/>


</android.support.constraint.ConstraintLayout>


다음은 프로젝트에 추가하는 방법에 대한 튜토리얼입니다.

ImageView를 화면의 절반과 동일하게 설정하려면 ImageView용 XML에 다음을 추가해야 합니다.

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

그런 다음 높이를 이 너비와 동일하게 설정하려면 코드로 해야 합니다.egetViewd방법GridView터 ,합니다.ImageView측정된 폭과 동일한 높이:

mImageView.getLayoutParams().height = mImageView.getMeasuredWidth();

2017년 현재 지나가는 사람들에게 원하는 것을 달성하는 가장 좋은 방법은 다음과 같은 제약 조건 레이아웃을 사용하는 것입니다.

<ImageView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    app:layout_constraintDimensionRatio="1:1" />

또한 레이아웃에 필요한 네 가지 방향 모두에 제약 조건을 추가하는 것도 잊지 마십시오.

제약 조건 레이아웃으로 응답형 UI 구축

또한 현재 Percent Relative Layout은 더 이상 사용되지 않습니다(Android 설명서 참조).

그 문제를 해결한 방법은 다음과 같습니다.

int pHeight =  picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));

preview - imageView 너비를 "match_parent"로 설정하고 축척합니다."cropCenter"를 입력합니다.

picture - imageView src에서 설정할 비트맵 개체입니다.

그것은 제게 꽤 효과적입니다.

할 수 것 이라고 생각하지 android:scaleType속성은 원하는 대로 작동합니다.
유일한 방법은 프로그래밍 방식으로 하는 것입니다.할 수 를 fill_parent로 설정할 수 .View또는 사용할 수 있습니다.View.getWidth()방법.

여기에는 ImageView "scaleType" 기능이 도움이 될 것입니다.

이 코드는 가로 세로 비율을 유지하고 이미지를 상단에 배치합니다.

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitStart"

scaleType을 사용할 때의 가능성과 모습을 보여주는 멋진 게시물입니다.

이미지 보기 축척유형시료

나는 이것을 했습니다.

layout.setMinimumHeight(layout.getWidth());

언급URL : https://stackoverflow.com/questions/9798392/imageview-have-height-match-width

반응형