IT

ImageView-높이가 너비와 일치합니까?

lottoking 2020. 6. 13. 09:35
반응형

ImageView-높이가 너비와 일치합니까?


이미지 뷰가 있습니다. 너비를 fill_parent로 설정하고 싶습니다. 높이가 너비가 무엇이든 되길 원합니다. 예를 들면 다음과 같습니다.

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

내 자신의 뷰 클래스를 만들지 않고도 레이아웃 파일에서 이와 같은 것이 가능합니까?

감사


업데이트 : 2017 년 9 월 14 일

아래의 의견에 따르면, 지원 라이브러리 비율은 Android 지원 라이브러리 26.0.0부터 더 이상 사용되지 않습니다. 이것이 새로운 방법입니다.

<android.support.constraint.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" />

</android.support.constraint.ConstraintLayout>

여기를 참조 하십시오

더 이상 사용되지 않음 :

Android Developers 의이 게시물따르면 이제 PercentRelativeLayout 또는 PercentFrameLayout 내에서 원하는 것을 랩핑 한 다음 비율을 지정하면됩니다.

<android.support.percent.PercentRelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        app:layout_widthPercent="100%"
        app:layout_aspectRatio="100%"/>

</android.support.percent.PercentRelativeLayout>

아마도 이것은 당신의 질문에 대답 할 것입니다 :

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

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


런타임에 Views 너비를 알고 나면 LayoutParams를 사용하여 Views 높이를 동적으로 설정할 수 있습니다. 런타임에 뷰 너비를 얻으려면 Runnable 스레드를 사용해야합니다. 그렇지 않으면 레이아웃이 아직 그려지지 않았기 때문에 뷰의 너비를 알기 전에 높이를 설정하려고합니다.

내 문제를 해결 한 방법의 예 :

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();
        }
    });

LayoutParams는보기가있는 부모보기 유형이어야합니다. 내 FrameLayout은 xml 파일의 RelativeLayout 안에 있습니다.

    mFrame.postInvalidate();

UI 스레드와 다른 스레드에있는 동안보기를 다시 그리도록 호출됩니다.


여기에 너비가 항상 높이와 같은 ImageButton을 사용하여 수행 한 것은 (한 방향으로 바보 같은 빈 여백을 피하십시오 ... 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"
           />

Works like a charm !


I couldn't get David Chu's answer to work for a RecyclerView item and figured out I needed to constrain the ImageView to the parent. Set the ImageView width to 0dp and constrain its start and end to the parent. I'm not sure if setting the width to wrap_content or match_parent works in some cases, but I think this is a better way to get the child of a ConstraintLayout to fill its parent.

<android.support.constraint.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"/>

</android.support.constraint.ConstraintLayout>

You can't do it with the layout alone, I've tried. I ended up writing a very simple class to handle it, you can check it out on github. SquareImage.java Its part of a larger project but nothing a little copy and paste can't fix (licensed under Apache 2.0)

Essentially you just need to set the height/width equal to the other dimension (depending on which way you want to scale it)

Note: You can make it square without a custom class using the scaleType attribute but the view's bounds extend beyond the visible image, which makes it an issue if you are placing other views near it.


In Android 26.0.0 PercentRelativeLayout has been deprecated.

The best way to solve it is now with ConstraintLayout like this:

<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>


Here is a tutorial on how to add ConstraintLayout to your project.


To set your ImageView equal to half the screen, you need to add the following to your XML for the ImageView:

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

To then set the height equal to this width, you need to do it in code. In the getView method of your GridView adapter, set the ImageView height equal to its measured width:

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

For people passing by now, in 2017, the new best way to achieve what you want is by using ConstraintLayout like this:

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

And don't forget to add constraints to all of the four directions as needed by your layout.

Build a Responsive UI with ConstraintLayout

Furthermore, by now, PercentRelativeLayout has been deprecated (see Android documentation).


Here's how I solved that problem:

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

preview - imageView with width setted to "match_parent" and scaleType to "cropCenter"

picture - Bitmap object to set in imageView src.

That's works pretty well for me.


I don't think there's any way you can do it in XML layout file, and I don't think android:scaleType attribute will work like you want it to be.
The only way would be to do it programmatically. You can set the width to fill_parent and can either take screen width as the height of the View or can use View.getWidth() method.


The ImageView "scaleType" function may help you here.

This code will keep the aspect ratio and position the image at the top:

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

Here is a great post showing the possibilities and appearances from using scaleType.

ImageView scaleType samples


If your image view is inside a constraint layout, you can use following constraints to create a square image view

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

참고URL : https://stackoverflow.com/questions/9798392/imageview-have-height-match-width

반응형