Share the post "How To Add Round Corners On ImageView XML In Android"
There was a previous post about this where you add round corners on an ImageView widget. That code can only be used programmatically so to be able to do the same thing within an XML file, a custom class has to be made in order for this to work.
User Devunwired of StackOverflow had made a custom class that works seamlessly and easily incorporate it in your XML.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class RoundedImageView extends ImageView { public RoundedImageView(Context context) { super(context); } public RoundedImageView(Context context, AttributeSet attrs) { super(context, attrs); } public RoundedImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { float radius = 10.0f; // angle of round corners Path clipPath = new Path(); RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight()); clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW); canvas.clipPath(clipPath); super.onDraw(canvas); } } |
To use it in XML, simply do it like this:
|
1 2 3 4 |
<my.package.RoundedImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/myimage" /> |
Thanks, tried that but it doesn’t seem to work, at least on my Nexus 7
@emanuele: did you use this for an app? or widget?
Thanks for this. Here there is a code based on yours that is better
for performance, as I moved allocation Path, RectF and radius to
Constructor. On OnDraw function it was allocated each time image was
drawn. Now, only ones:
http://pastebin.com/BAu9viXL
hi tom, you are right. it is better to move those variables outside so they be instantiated only once
it’s worked..Thank You.. :))