gpt4 book ai didi

android - 固定纵横比 View

转载 作者:IT王子 更新时间:2023-10-29 00:00:27 25 4
gpt4 key购买 nike

我将如何实现一个固定的纵横比View?我想在 GridView 中有 1:1 纵横比的项目。我认为子类化子类比 GridView 更好?

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

最佳答案

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

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

关于android - 固定纵横比 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com