50

我将如何实施固定的纵横比View?我想在GridView. 我认为子类化孩子比GridView?

编辑:我认为这需要以编程方式完成,这没问题。另外,我不想限制大小,只限制纵横比。

4

9 回答 9

85

我实现了 FixedAspectRatioFrameLayout,所以我可以重用它并使任何托管视图具有固定的纵横比:

public class FixedAspectRatioFrameLayout extends FrameLayout
{
    private int mAspectRatioWidth;
    private int mAspectRatioHeight;

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

    public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        init(context, attrs);
    }

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

        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs)
    {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectRatioFrameLayout);

        mAspectRatioWidth = a.getInt(R.styleable.FixedAspectRatioFrameLayout_aspectRatioWidth, 4);
        mAspectRatioHeight = a.getInt(R.styleable.FixedAspectRatioFrameLayout_aspectRatioHeight, 3);

        a.recycle();
    }
    // **overrides**

    @Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)
    {
        int originalWidth = MeasureSpec.getSize(widthMeasureSpec);

        int originalHeight = MeasureSpec.getSize(heightMeasureSpec);

        int calculatedHeight = originalWidth * mAspectRatioHeight / mAspectRatioWidth;

        int finalWidth, finalHeight;

        if (calculatedHeight > originalHeight)
        {
            finalWidth = originalHeight * mAspectRatioWidth / mAspectRatioHeight; 
            finalHeight = originalHeight;
        }
        else
        {
            finalWidth = originalWidth;
            finalHeight = calculatedHeight;
        }

        super.onMeasure(
                MeasureSpec.makeMeasureSpec(finalWidth, MeasureSpec.EXACTLY), 
                MeasureSpec.makeMeasureSpec(finalHeight, MeasureSpec.EXACTLY));
    }
}
于 2012-05-27T08:11:25.797 回答
38

对于新用户,这里有一个更好的非代码解决方案:

Android SDK v22 中提供了一个名为Percent Support Library的新支持库(我认为 MinAPI 为7,不确定):

源代码:android-developers.blogspot.in

百分比支持库提供基于百分比的尺寸和边距,并且在此版本中新增了通过 app:aspectRatio 设置自定义纵横比的能力。通过仅设置单个宽度或高度并使用 aspectRatio,PercentFrameLayout 或 PercentRelativeLayout 将自动调整其他尺寸,以便布局使用设置的纵横比。

要将其添加到您的build.gradle 中

compile 'com.android.support:percent:23.1.1'

PercentRelativeLayout现在用/包裹你的视图(需要是方形的)PercentFrameLayout

<android.support.percent.PercentRelativeLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content">
     <ImageView
         app:layout_aspectRatio="100%"
         app:layout_widthPercent="100%"/>
 </android.support.percent.PercentRelativeLayout>

你可以在这里看到一个例子。

于 2016-02-15T22:14:30.440 回答
32

为了不使用第三方解决方案并考虑到 PercentFrameLayout 和 PercentRelativeLayout 在 26.0.0 中已被弃用,我建议您考虑使用 ConstraintLayout 作为网格项的根布局。

item_grid.xml可能看起来像:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageview_item"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="H,1:1" />

</android.support.constraint.ConstraintLayout>

结果你会得到这样的东西:

固定比例大小的网格项目

于 2017-09-25T15:40:35.573 回答
9

我最近为这个问题创建了一个帮助类,并写了一篇关于它的博客文章

代码的实质如下:

/**
 * Measure with a specific aspect ratio<br />
 * <br />
 * @param widthMeasureSpec The width <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method
 * @param heightMeasureSpec The height <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method
 * @param aspectRatio The aspect ratio to calculate measurements in respect to 
 */
public void measure(int widthMeasureSpec, int heightMeasureSpec, double aspectRatio) {
    int widthMode = MeasureSpec.getMode( widthMeasureSpec );
    int widthSize = widthMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( widthMeasureSpec );
    int heightMode = MeasureSpec.getMode( heightMeasureSpec );
    int heightSize = heightMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( heightMeasureSpec );

    if ( heightMode == MeasureSpec.EXACTLY && widthMode == MeasureSpec.EXACTLY ) {
        /* 
         * Possibility 1: Both width and height fixed
         */
        measuredWidth = widthSize;
        measuredHeight = heightSize;

    } else if ( heightMode == MeasureSpec.EXACTLY ) {
        /*
         * Possibility 2: Width dynamic, height fixed
         */
        measuredWidth = (int) Math.min( widthSize, heightSize * aspectRatio );
        measuredHeight = (int) (measuredWidth / aspectRatio);

    } else if ( widthMode == MeasureSpec.EXACTLY ) {
        /*
         * Possibility 3: Width fixed, height dynamic
         */
        measuredHeight = (int) Math.min( heightSize, widthSize / aspectRatio );
        measuredWidth = (int) (measuredHeight * aspectRatio);

    } else {
        /* 
         * Possibility 4: Both width and height dynamic
         */
        if ( widthSize > heightSize * aspectRatio ) {
            measuredHeight = heightSize;
            measuredWidth = (int)( measuredHeight * aspectRatio );
        } else {
            measuredWidth = widthSize;
            measuredHeight = (int) (measuredWidth / aspectRatio);
        }

    }
}
于 2012-12-12T18:53:32.257 回答
5

我使用TalL的答案创建了一个布局库。随意使用它。

比例布局

安装

将此添加到文件顶部

repositories {
    maven {
        url  "http://dl.bintray.com/riteshakya037/maven" 
    }
}


dependencies {
    compile 'com.ritesh:ratiolayout:1.0.0'
}

用法

在布局的根视图上定义“app”命名空间

xmlns:app="http://schemas.android.com/apk/res-auto"

在你的布局中包含这个库

<com.ritesh.ratiolayout.RatioRelativeLayout
        android:id="@+id/activity_main_ratio_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:fixed_attribute="WIDTH" // Fix one side of the layout 
        app:horizontal_ratio="2" // ratio of 2:3
        app:vertical_ratio="3">

更新

随着ConstraintLayout的引入,您不必编写任何一行代码或使用第三方或依赖PercentFrameLayout于 26.0.0 中已弃用的第三方。

以下是如何使用以下方法为您的布局保持 1:1 纵横比的示例ConstraintLayout

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

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        android:background="@android:color/black"
        app:layout_constraintDimensionRatio="H,1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </LinearLayout>

</android.support.constraint.ConstraintLayout>
于 2017-05-30T06:46:02.763 回答
4

我已经使用并喜欢 Jake Wharton 的实现ImageView(对于其他观点应该类似),其他人可能也会喜欢它:

AspectRatioImageView.java -尊重应用于特定测量的纵横比的 ImageView

好东西它已经可以在 xml 中设置样式了。

于 2014-08-24T20:16:06.903 回答
3

只需在那里覆盖onSizeChanged并计算比率。

纵横比的公式是:

newHeight =  original_height / original_width x new_width

这会给你类似的东西:

 @Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    //3:5 ratio
    float RATIO = 5/3;
    setLayoutParams(new LayoutParams((int)RATIO * w, w));

}

希望这可以帮助!

于 2013-02-13T13:41:53.540 回答
2

谷歌的 ExoPlayer 带有一个AspectRatioFrameLayout,你可以这样使用:

<com.google.android.exoplayer2.ui.AspectRatioFrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">
    <!-- https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.html#RESIZE_MODE_FIXED_WIDTH -->

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.google.android.exoplayer2.ui.AspectRatioFrameLayout>

然后您必须以编程方式设置纵横比:

aspectRatioFrameLayout.setAspectRatio(16f/9f)

请注意,您还可以使用 以编程方式设置调整大小模式setResizeMode


由于您显然不会为这个单一类获取整个 ExoPlayer 库,您可以简单地将文件从 GitHub 复制粘贴到您的项目(它是开源的):

https://github.com/google/ExoPlayer/blob/release-v2/library/ui/src/main/java/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.java

不要忘记获取属性resize_mode

https://github.com/google/ExoPlayer/blob/release-v2/library/ui/src/main/res/values/attrs.xml#L18-L25

<attr name="resize_mode" format="enum">
  <enum name="fit" value="0"/>
  <enum name="fixed_width" value="1"/>
  <enum name="fixed_height" value="2"/>
  <enum name="fill" value="3"/>
  <enum name="zoom" value="4"/>
</attr>
于 2019-05-27T10:47:27.413 回答
1

您可能会找到第三方库。不要使用它们,而是使用约束布局。下面的代码将 ImageView 的纵横比设置为 16:9,无论屏幕大小和方向如何。

<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:scaleType="fitXY"
        android:src="@drawable/mat3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintDimensionRatio="H,16:9"/>

</androidx.constraintlayout.widget.ConstraintLayout>

app:layout_constraintDimensionRatio="H,16:9". 这里,高度是相对于布局的宽度设置的。

肖像活动

景观活动

对于您的问题,在您的视图中设置android:layout_width="match_parent"和使用。app:layout_constraintDimensionRatio="H,1:1"

于 2020-08-25T17:06:41.920 回答