mcfly soft
mcfly soft

Reputation: 11645

draw path with hole ( android )

Does anyone have a hint for me for the following problem ?

I would like to draw a filled path ( canvas ) which has a hole in it. In SVG the path definition is the follow :

M 100 100 L 200 100 L 200 200 L 100 200 L 100 100 z
M 125 125 L 175 125 L 175 175 L 125 175 L 125 125 z

I would like to draw this path ( shape ) without path subtract path ( because of specific software design )

My try with java draws me a full square without a hole. I am wondering, why an SVG viewer draws the hole with the mentoined definition and the java canvas doesn't ? where is the difference ? How can I achieve this ?

            Path p=new Path();
        p.moveTo(100, 100);
        p.lineTo(200,100);
        p.lineTo(200,200);
        p.lineTo(100,200);
        p.close();
        p.moveTo(150, 150);
        p.moveTo(180, 150);
        p.moveTo(180, 180);
        p.moveTo(150, 180);
        p.close();
        canvas.drawPath(p, paint);

Any hint ?

regards

Upvotes: 12

Views: 14182

Answers (2)

Robert Longson
Robert Longson

Reputation: 123995

SVG determines what's inside/outside a path by using the fill-rule. Java also allows a winding rule to be set. With Android paths there is also a fillType which works similarly. Perhaps you have different rules set for the java or SVG code?

Upvotes: 0

Vladimir Mironov
Vladimir Mironov

Reputation: 30864

You should use Path.setFillType(Path.FillType.EVEN_ODD):

final Path path = new Path();
final Paint paint = new Paint();

paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL_AND_STROKE);

path.moveTo(100, 100);
path.lineTo(200, 100);
path.lineTo(200, 200);
path.lineTo(100, 200);
path.close();

path.moveTo(150, 150);
path.lineTo(180, 150);
path.lineTo(180, 180);
path.lineTo(150, 180);
path.close();

path.setFillType(Path.FillType.EVEN_ODD);
canvas.drawPath(path, paint);

Upvotes: 37

Related Questions