2

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 ...

medo
  • 479
  • 3
  • 9
  • 24

1 Answers1

1

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?

babay
  • 4,689
  • 1
  • 26
  • 40
  • but i have drawable not bitmap :/ – medo Oct 02 '17 at 22:55
  • what kind of drawable do you have? the easiest way is to draw that drawable into bitmap. But if you specify a drawable type you use, may be I'll be able to show, how to draw that drawable in circle. – babay Oct 02 '17 at 23:07
  • my drawable its class extend `drawable` – medo Oct 02 '17 at 23:08
  • i tried on drawable class `canvas.drawRoundRect(new RectF(0,0,getBounds().width(), getBounds().height()), g, g, paintx);` but the old draw (IMAGES) its shown outside the circle – medo Oct 02 '17 at 23:21
  • Added fix. Just use `canvas.clipPath()` to clip drawable to any path. Circular, for example. – babay Oct 02 '17 at 23:35
  • clipPath and antialias :/ – medo Oct 02 '17 at 23:49
  • https://stackoverflow.com/questions/2719535/how-do-i-antialias-the-clip-boundary-on-androids-canvas https://stackoverflow.com/questions/37748652/antialias-on-clippath-on-layout – babay Oct 02 '17 at 23:55