Skip to content

Instantly share code, notes, and snippets.

@holmeszyx
Created April 19, 2014 07:36
Show Gist options
  • Select an option

  • Save holmeszyx/11077012 to your computer and use it in GitHub Desktop.

Select an option

Save holmeszyx/11077012 to your computer and use it in GitHub Desktop.
FixImageView 自动调整等比高宽
package com.example.imagetext.view;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class FixImageView extends ImageView{
private int mFixWidth = -1;
public FixImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init();
}
public FixImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
public FixImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
init();
}
private void init(){
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// It is Auto-generated method stub
if (mFixWidth > 0){
widthMeasureSpec = MeasureSpec.makeMeasureSpec(mFixWidth, MeasureSpec.EXACTLY);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
return;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void setImageDrawable(Drawable drawable) {
// It is Auto-generated method stub
float height = getHeight();
mFixWidth = (int) ((height / drawable.getIntrinsicHeight()) * drawable.getIntrinsicWidth());
System.out.println(String.format("h:%f, fixw: %d, dh: %d, dw: %d", height, mFixWidth, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()));
requestLayout();
super.setImageDrawable(drawable);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment