在画布上绘制波形形状(Android) [英] Drawing a squircle shape on canvas (Android)

查看:222
本文介绍了在画布上绘制波形形状(Android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来在画布上绘制圆形形状(然后在其上绘制图标位图)的东西:

Here is what I'm using to draw a circle shape on to the canvas (and then an icon bitmap on it):

private static Bitmap makeIcon(int radius, int color, Bitmap icon) {
    final Bitmap output = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(output);
    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(color);
    canvas.drawARGB(0, 0, 0, 0);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
        canvas.drawCircle(radius / 2, radius / 2, radius / 2, paint);
    else
        canvas.drawRect(0, 0, radius, radius, paint);
    int cx = (radius - icon.getWidth()) >> 1; // same as (...) / 2
    int cy = (radius - icon.getHeight()) >> 1;
    canvas.drawBitmap(icon, cx, cy, paint);
    icon.recycle();
    return output;
}

但是我不知道如何绘制圆盘形而不是圆形.仅供参考,以下是一些使用鼠形形状的图标的示例:

But I have no idea on how to draw a squircle shape instead of the circle shape. FYI, here are some examples of icons using the squircle shape:

推荐答案

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Path squirclePath = getSquirclePaath(150, 250, 400);
        canvas.drawPath(squirclePath, mPaint);
    }

    private static Path getSquirclePaath(int left, int top, int radius){
        //Formula: (|x|)^3 + (|y|)^3 = radius^3
        final double radiusToPow = radius * radius * radius;

        Path path = new Path();
        path.moveTo(-radius, 0);
        for (int x = -radius ; x <= radius ; x++)
            path.lineTo(x, ((float) Math.cbrt(radiusToPow - Math.abs(x * x * x))));
        for (int x = radius ; x >= -radius ; x--)
            path.lineTo(x, ((float) -Math.cbrt(radiusToPow - Math.abs(x * x * x))));
        path.close();

        Matrix matrix = new Matrix();
        matrix.postTranslate(left + radius, top + radius);
        path.transform(matrix);

        return path;
    }

希望这会有所帮助,以下是预览:

Hope this helps, here is a preview:

这篇关于在画布上绘制波形形状(Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆