Marc Bacvanski
Marc Bacvanski

Reputation: 1538

Android Creating Bitmap Size on Screen Density

In my app I need to make bitmap icons that get overlaid on a Google Map View like so.

public Bitmap makeBubble(int radius, int color) {
    Bitmap bm = Bitmap.createBitmap(radius * 2, radius * 2, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(color);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawCircle(bm.getWidth() / 2, bm.getHeight() / 2, radius, paint);

    paint.setColor(Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)));
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawCircle(bm.getWidth() / 2, bm.getHeight() / 2, radius, paint);
    return bm;
}

However, these icons have significantly different sizes on different screen densities (as would be expected).

How do I create them in the same size on all screen densities?

Upvotes: 0

Views: 363

Answers (1)

Pedro Loureiro
Pedro Loureiro

Reputation: 11514

The best way to do it is defining a dimension in XML: (you can rename it)

<!-- file: /res/values/dimentions.xml (you can rename the file) -->
<resources>
    <dimen name="circle_radius">24dp</dimen>
</resources>

And then wherever you call this function makeBubble do this:

int radius  = context.getResources().getDimensionPixelSize(R.dimen.circle_radius);
makeBubble(radius, color)

You can get a context or resources from Activity, Fragment or View so you probably can get one of these. Don't use the application context as that will give you some problems in edge conditions.

Update:

After your comment, you seem to need to calculate the value programmatically. Just multiply your radius by DisplayMetrics.density

Here's how to do it:

DisplayMetrics metrics = getResources().getDisplayMetrics();
int radius = ...; // original calculation
radius *= metrics.density; // now this is adjusted for screen density

Here's the documentation

Upvotes: 1

Related Questions