简体   繁体   English

在画布上绘制圆

[英]draw circle Drawable in canvas

i have an canvas with width 400 and height 100 i just draw on it some thing 我有一块width 400height 100的画布,我只是在上面画一些东西

and now i want to draw a Drawable 现在我想画一个Drawable

i draw it like this 我这样画

@Override
protected void onDraw(Canvas canvas) {

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

}

now the result its would be 现在的结果是

在此处输入图片说明

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 我想要的只是使Drawable Rounded我看到了RoundedImageView类的类,但我没有找到将Drawable转换成圆形并在画布上绘制的好主意,而不是在画布上的所有小部分

final result must be like 最终结果一定是

在此处输入图片说明

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 ... 请仔细阅读问题,然后使其重复,我想在画布的一部分而不是在所有画布上绘制圆形可绘制的对象,因为我提到我阅读了某些类代码,例如RoundedImageView ...

You can use RoundedBitmapDrawable of android.support.v4 . 您可以使用android.support.v4 RoundedBitmapDrawable

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: 如果需要在(x,y)处绘制可绘制对象,则应平移画布:

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

You can use canvas.cliPath() to clip drawable to any path: 您可以使用canvas.cliPath()将可绘制对象剪切到任何路径:

    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 布局上的clipPath上的抗锯齿

How do I antialias the clip boundary on Android's canvas? 如何在Android画布上对剪辑边界进行锯齿处理?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM