沿圆形矩形路径Android绘制元素

时间:2015-01-11 18:08:09

标签: android canvas android-canvas

我正在建造一个表盘,我想沿圆角矩形路径绘制刻度,但我不知道应该从哪里开始。

是否有一种方法可以创建一个形状(在这种情况下为圆形矩形),然后每x个像素获得一个点?

1 个答案:

答案 0 :(得分:0)

这应该让你开始。

    //Path for a rounded rectangle.
    path = new Path();
    path.moveTo(rx, 0);
    path.lineTo(width - rx, 0);
    path.quadTo(width, 0, width,ry);
    path.lineTo(width, height-ry);
    path.quadTo(width, height, width-rx,height);
    path.lineTo(rx, height);
    path.quadTo(0,height, 0, height-ry);
    path.lineTo(0,ry);
    path.quadTo(0, 0, rx, 0);
    //valid APIs less than 21.

    float centerX = (x+width)/2;
    float centerY = (y+height)/2;
    //get center point

    int number_of_ticks = 60;
    int amount_towards_center = 10;

    ticks =  new Path();
    PathMeasure pathMeasure = new PathMeasure(path, false);
    float fSegmentLen = pathMeasure.getLength() / number_of_ticks;
    float afP[] = {0f, 0f};

    for (int i = 0; i < number_of_ticks; i++) {
        pathMeasure.getPosTan(fSegmentLen * i, afP, null);
        ticks.moveTo(afP[0], afP[1]);
        float dX = (centerX-afP[0]) / amount_towards_center;
        float dY = (centerY-afP[1]) / amount_towards_center;
        ticks.lineTo(afP[0]+dX, afP[1]+dY);
    }

事实上,如果你不想得到幻想,它也可能让你完成。

@Override
public void draw(Canvas canvas, Paint paint) {
    canvas.drawPath(ticks,paint);
    canvas.drawPath(path,paint);
}

并且没有填充:

    paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);