b_yng
b_yng

Reputation: 14136

Adjust BitmapDrawable or bitmap dimensions

I am trying to create a tab-like interface where I will switch views by sliding left/right. I display to the user what page they are on by adding a blue glow to the back of the tab icon shown here:


I did this by creating a custom view that will draw the background glow (if the tab is selected) and then the icon. My issue is that the glow is too large. All I need to do is to make it smaller so the sides don't get clipped like they are now (the glow overlaps the page on the bottom by design).


Constructor:

public TabIconView(Context context, Bitmap tab)
{
    super(context);

    back = BitmapFactory.decodeResource(getResources(), R.drawable.background_blue_glow);
    this.tab = tab;
}

onMeasure and onDraw:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    setMeasuredDimension(tab.getWidth() * 2, tab.getHeight() * 2);
}

@Override
protected void onDraw(Canvas canvas)
{
    width = getMeasuredWidth();
    height = getMeasuredHeight();

    if (selected)
        canvas.drawBitmap(back, (width - back.getWidth()) / 2, (height - back.getHeight()) / 2, null);

    canvas.drawBitmap(tab, (width - tab.getWidth()) / 2, (height - tab.getHeight()) / 2, null);

    super.onDraw(canvas);
}

Any ideas will be greatly appreciated.

Upvotes: 0

Views: 617

Answers (2)

b_yng
b_yng

Reputation: 14136

Figured it out. In case anybody wants to know...

public TabIconView(Context context, Bitmap tab)
{
    super(context);
    int backSize = (int) (42 * context.getResources().getDisplayMetrics().density + .5f);

    b = BitmapFactory.decodeResource(getResources(), R.drawable.background_blue_glow);
    back = Bitmap.createScaledBitmap(b, backSize, backSize, false);
    this.tab = tab;
}

I had to create a scaled bitmap from the bitmap that was generated from the shapedrawable.

Upvotes: 1

Romain Guy
Romain Guy

Reputation: 98501

One of the versions of Canvas.drawBitmap() lets you specified the width and height that you want the bitmap to have when drawn on screen. You could also simply rescale the bitmap when you load it (the Bitmap class has methods to create scaled versions of bitmaps.)

Upvotes: 1

Related Questions