Skip to content

Instantly share code, notes, and snippets.

@Xenofex
Created March 10, 2015 11:14
Show Gist options
  • Save Xenofex/25db4d087afe5b9e3b5e to your computer and use it in GitHub Desktop.
Save Xenofex/25db4d087afe5b9e3b5e to your computer and use it in GitHub Desktop.
package com.lettrs.lettrs.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import com.lettrs.lettrs.R;
import lombok.Getter;
import lombok.Setter;
/**
* This class will try to maintain its aspect ratio according to the parameter aspectRatio,
* (styleable via attribute 'aspect_ratio').
*
* If the width is not zero, it will try to change the height to maintain the aspect ratio.
* Otherwise it tries to change the width. If non of these works, it fallbacks to a regular layout.
*
* If the aspectRatio is not present (less than 0.0f), it will fallback to a regular layout
*/
public class FixedAspectRatioLayout extends RelativeLayout {
/**
* width / height
*/
@Getter @Setter
private float aspectRatio;
public FixedAspectRatioLayout(Context context) {
super(context);
}
public FixedAspectRatioLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FixedAspectRatioLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectRatioLayout, defStyle, 0);
try {
aspectRatio = typedArray.getFloat(R.styleable.FixedAspectRatioLayout_aspect_ratio, Float.MIN_VALUE);
} finally {
typedArray.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (aspectRatio > 0) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (width > 0 && width < height) {
int measuredHeight = (int) (width / aspectRatio);
super.onMeasure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.getMode(heightMeasureSpec)));
} else if (height > 0 && height <= width) {
int measuredWidth = (int) (height * aspectRatio);
super.onMeasure(MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.getMode(widthMeasureSpec)),
heightMeasureSpec);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
@Xenofex
Copy link
Author

Xenofex commented Mar 10, 2015

Add this to attrs.xml

    <declare-styleable name="FixedAspectRatioLayout">
        <attr name="aspect_ratio" format="float"/>
    </declare-styleable>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment