Oliver Dixon
Oliver Dixon

Reputation: 7414

Screen size percentage calculator returning wrong size

I have a function I use in order to return bitmaps from the drawable folder. (I don't use the drawable DPI folders, waste of time)

Anyhow the function retrieves bitmaps, the bitmaps are returned as a specified percentage of the view port size.

At the moment it's returning less than the specified percentage for example the ground element:

The percentage should be a 100% of the width which is 480 pixels. Obviously this should be 480 but it's returning 400? I must be missing some simple maths out here or something anyhow the code is below: (also should I be using createscaledbitmap?)

public Bitmap getBitmapSized(String name, int percentage, int screen_dimention, int frames, int rows)
{
    _tempInt = _context.getResources().getIdentifier(name, "drawable", _context.getPackageName());
    _tempbitmap = (BitmapFactory.decodeResource(_context.getResources(), _tempInt, _BM_options));

    _bmWidth = _tempbitmap.getWidth() / frames;
    _bmHeight = _tempbitmap.getHeight() / rows;

    _newWidth = (screen_dimention / 100) * percentage;
    _newHeight = (_newWidth / _bmWidth) * _bmHeight;

    //Round up to closet factor of total frames (Stops juddering within animation)
    _newWidth = _newWidth * frames;

    //Output the created item
    Log.w("Screen Width: ", Integer.toString(screen_dimention));
    Log.w(name, "Item");
    Log.w(Integer.toString((int)_newWidth), "new width");
    Log.w(Integer.toString((int)_newHeight), "new height");

    //Create new item and recycle bitmap
    Bitmap newBitmap = Bitmap.createScaledBitmap(_tempbitmap, (int)_newWidth, (int)_newHeight, false);
    _tempbitmap.recycle();
    System.gc();

    return newBitmap;
}

Upvotes: 0

Views: 190

Answers (1)

Don Roby
Don Roby

Reputation: 41137

_newWidth = (screen_dimention / 100) * percentage;

is doing integer division.

You may want

_newWidth = (screen_dimention / 100.0) * percentage;

or if _newWidth is actually supposed to be truncated to an integer, you may want

_newWidth = (screen_dimention * percentage) / 100;

to have the truncation later.

Upvotes: 3

Related Questions