lunes, 12 de mayo de 2014

Android: Resizable ImageView (according to image preserving proportion, viewTreeObserver)

public class MyImageView extends ImageView {

private int imageWidth;
private int imageHeight;

public MyImageView(Context context) {

super(context);

addGlobalLayoutListener();
}

private void addGlobalLayoutListener() {

this.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {

resize(imageWidth, imageHeight);

removeOnGlobalLayoutListener(MyImageView.this);
}

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void removeOnGlobalLayoutListener(final View image) {

int currentAPIVersion = android.os.Build.VERSION.SDK_INT;

if (currentAPIVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
image.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
image.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}

public MyImageView(Context context, AttributeSet attrs) {

super(context, attrs);

addGlobalLayoutListener();
}

public MyImageView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

addGlobalLayoutListener();
}

@Override
public void setImageBitmap(Bitmap bm) {

super.setImageBitmap(bm);

resize(bm.getWidth(), bm.getHeight());
}

@Override
public void setImageDrawable(Drawable drawable) {

super.setImageDrawable(drawable);
}

@Override
public void setImageResource(int resId) {

super.setImageResource(resId);
}

private void resize(int imageWidth, int imageHeight) {

int imageViewWidth = this.getWidth();

if ((imageViewWidth != 0) && (imageWidth != 0)) {

int newImageViewHeight = imageViewWidth * imageHeight / imageWidth;

this.setLayoutParams(new LayoutParams(imageViewWidth, newImageViewHeight));
}
else {

this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
}
}

}

No hay comentarios:

Publicar un comentario