qbo
qbo

Reputation: 386

Set bitmap to ImageView with specific height

I have an ImageView and a bitmap I pull from my server but I am having trouble setting the bitmap to ImageView in a way I would like.

For example here are the components I'm working with:

I would like my bitmap to be set on ImageView vertically centered.

Another example is, if I had an ImageView with the same dimensions and Bitmap is 100px wide and 100px high, I would like the bitmap to take the width of the ImageView (300px) and vertically centered after being scaled.

How can I achieve this without implementing any bitmap size logic?

Upvotes: 0

Views: 108

Answers (2)

sky
sky

Reputation: 206

/** * @author sky */ public class BitmapImageView extends ImageView {

public BitmapImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public BitmapImageView(Context context) {
    super(context);
}

private BitmapDrawable imageDrawable;

@Override
public final void setImageDrawable(Drawable drawable) {
    super.setImageDrawable(drawable);
    if (drawable instanceof BitmapDrawable) {
        imageDrawable = (BitmapDrawable) drawable;
    } else {
        imageDrawable = null;
    }
}

@Override
protected void onDraw(Canvas canvas) {
    //
    if (imageDrawable == null) {
        super.onDraw(canvas);
        return;
    }
    Bitmap imgBitmap = imageDrawable.getBitmap();
    if (imgBitmap == null || imgBitmap.isRecycled()) {
        super.onDraw(canvas);
        return;
    }
    int dw = imgBitmap.getWidth();
    int dh = imgBitmap.getHeight();
    if (dw <= 0 || dh <= 0) {
        super.onDraw(canvas);
        return;
    }
    float scale = getWidth() / (float) dw;
    //
    float topOffsetAfterScale = -(dh * scale - getHeight()) / 2f;
    int save_count = canvas.save();
    canvas.translate(0, topOffsetAfterScale);
    canvas.scale(scale, scale);
    canvas.drawBitmap(imgBitmap, 0, 0, imageDrawable.getPaint());
    canvas.restoreToCount(save_count);
}

}

Upvotes: 0

saiful103a
saiful103a

Reputation: 1129

You should take a look into this: Loading Bitmap , you can reduce the size of your bitmap efficiently using the method provided in that link. And also if you had an imageview with a higher dimension then your bitmap use scaletype property of ImageView.

Some hint to use scaletype property:

            if (myBitmap.getWidth() > myBitmap
            .getHeight()
                && myBitmap.getWidth() > 300
                && myBitmap.getHeight() > 200) {

            ((ImageView) view)
                    .setScaleType(ScaleType.FIT_XY);

        } else {
            ((ImageView) view)
                .setScaleType(ScaleType.FIT_CENTER);
        }

Upvotes: 0

Related Questions