-
-
Save CMingTseng/02460500c315aa766c53a00b293cd35a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.content.res.TypedArray; | |
import android.util.AttributeSet; | |
import android.widget.ImageView; | |
/** | |
* TODO: Add a class header comment! | |
*/ | |
public class AspectRatioImageView extends ImageView { | |
private float mAspectRatio; | |
public AspectRatioImageView(Context context) { | |
this(context, null); | |
} | |
public AspectRatioImageView(Context context, AttributeSet attrs) { | |
this(context, attrs, 0); | |
} | |
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AspectRatioImageView); | |
mAspectRatio = a.getFloat(R.styleable.AspectRatioImageView_aspect_ratio, -1); | |
a.recycle(); | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
if (mAspectRatio > 0) { | |
int width = getMeasuredWidth(); | |
int height = (int) (width * mAspectRatio); | |
setMeasuredDimension(width, height); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="AspectRatioImageView"> | |
<attr name="aspect_ratio" format="float" /> | |
</declare-styleable> | |
</resources> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment