2

I need to be able to mask an image in my layout to have rounded corners. Is there a simple way to specify an alpha mask in the layout? I would like to avoid having to manually mask each bitmap I'm using.


EDIT

Here is my code, as referenced to the other answer:

HttpURLConnection connection = (HttpURLConnection) this.items.get(position).getIcon().toURL().openConnection();
connection.setDoInput(true);
connection.connect();

Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());

Integer dimension = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getWidth() :
        bitmap.getHeight();

Bitmap rounder = Bitmap.createBitmap(dimension, dimension, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(rounder);

Paint painter = new Paint(Paint.ANTI_ALIAS_FLAG);
painter.setColor(Color.RED);

canvas.drawRoundRect(new RectF(0, 0, dimension, dimension), 
        20.0F, 20.0F, painter);

painter.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

canvas.drawBitmap(bitmap, 0, 0, null);
canvas.drawBitmap(rounder, 0, 0, painter);

holder.image.setImageBitmap(bitmap);

However, this doesn't work. I don't see see rounded corners, I see the regular image as-is. Is there a step at the end I'm missing that involves the canvas?

Community
  • 1
  • 1
Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
  • 2
    Have a look at this question http://stackoverflow.com/questions/1705239/how-should-i-give-images-rounded-corners-in-android – Damp Feb 15 '11 at 16:16

2 Answers2

2

Looks like your question was answered before, perhaps this might help?

Community
  • 1
  • 1
VoronoiPotato
  • 3,113
  • 20
  • 30
  • It helps, but how do I set my ImageView's bitmap to be the rounded one? The last step seems to be missing from his answer :( – Naftuli Kay Feb 15 '11 at 19:35
  • I have modified my question to include the code I'm using which doesn't work. – Naftuli Kay Feb 15 '11 at 19:55
  • My link was different from damp's, mine iterated through the image as an array of lists, and where the alpha mask was red (another picture), made the main picture clear. An elegant kind of primal solution to the problem. I don't know if it's necessarily the best solution, but it seems pretty solid. – VoronoiPotato Feb 16 '11 at 03:45
  • The answer applies to pure java programs. I'm sure that in Android you can achieve better and faster results if you are using a Canvas. But I'm searching for a good answer on something like this too. – Janusz Feb 09 '12 at 08:58
1

There are a few ways you could acomplish this . I would make a nine patch that is transparent except for the corners and draw that on top of the images.

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156