medo
medo

Reputation: 479

draw circle Drawable in canvas

i have an canvas with width 400 and height 100 i just draw on it some thing

and now i want to draw a Drawable

i draw it like this

@Override
protected void onDraw(Canvas canvas) {

    iconDrawable.draw(canvas);
    // ... draw other thing

}

now the result its would be

enter image description here

what i want its only make the Drawable Rounded i seen some class like RoundedImageView and other but i didn't find good idea for convert my Drawable to circle and draw it in canvas not on all canvas small part on it

final result must be like

enter image description here

please read question carefully before make it duplicate i want rounded drawable on part of canvas not on all canvas as i mentioned i read some class code like RoundedImageView ...

Upvotes: 2

Views: 1560

Answers (1)

babay
babay

Reputation: 4844

You can use RoundedBitmapDrawable of android.support.v4.

Bitmap bm = ...;
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), bm);
drawable.setCornerRadius(Math.min(bm.getWidth(), bm.getHeight()));
drawable.setAntiAlias(true);
....
drawable.draw(canvas);

If you need to scale a drawable (set it's size), you should use

drawable.setBounds(0, 0, width, height);

If you need to draw a drawable at (x,y) you should translate the canvas:

canvas.save();
canvas.translate(x, y);
drawable.draw(canvas);
canvas.restore();

You can use canvas.cliPath() to clip drawable to any path:

    Rect b = drwable.getBounds();

    canvas.save();
    Path path = new Path();
    int w = b.right;
    int h = b.bottom;
    path.addCircle(w/2, h/2, w/2, Path.Direction.CW);
    canvas.clipPath(path);
    drawable.draw(canvas);
    canvas.restore();

if you need antialiasing, you can try theese questions:

Antialias on clipPath on layout

How do I antialias the clip boundary on Android's canvas?

Upvotes: 1

Related Questions