Search code examples
androidandroid-imageviewandroid-image

Where should you apply transformations when extending Android ImageView's?


I'm making a custom component which extends ImageView on Android. The components function is fairly complicated - to always fill the height of its container by scaling but to trim empty space on the width. It will also automatically apply a 90 degree rotation transformation if the width is bigger than the height, before applying any scaling.

I know how to do these transformations and have output their results to file so I know they work correctly. What I don't know is where/what methods to do this in when extending the View.

I'm not including the transformation code for now because it doesn't seem relevant but below shows where I call these transformations currently

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mConversionComplete) {
        applyTransformations(widthMeasureSpec, heightMeasureSpec);
    }
    Drawable imageDrawable = getDrawable();
    if (imageDrawable != null) {
        int height = MeasureSpec.getSize(MeasureSpec.AT_MOST);
        int width = (int) Math.ceil((float) height * (float)     imageDrawable.getIntrinsicWidth() / (float) imageDrawable.getIntrinsicHeight());
        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

I am currently doing the transformations from onMeasure as I need to be able to use the measure specs (below). I record whether I have handled the transformations so that I only do them once, but I think there's probably a 'right' place to do this which isn't onMeasure

int targetHeight = MeasureSpec.getSize(heightMeasureSpec);
int targetWidth = MeasureSpec.getSize(widthMeasureSpec);

Solution

  • Based on your description of your customization you should limit your scope to determining the dimensions of the ImageView and using setImageMatrix. Let the android system do the hard work for you.