2 Copyright 2006 Jerry Huxtable
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
17 package org.simantics.scenegraph.utils;
19 import java.awt.Shape;
20 import java.awt.Stroke;
21 import java.awt.geom.AffineTransform;
22 import java.awt.geom.FlatteningPathIterator;
23 import java.awt.geom.GeneralPath;
24 import java.awt.geom.PathIterator;
25 import java.awt.geom.Rectangle2D;
28 * Taken from http://www.jhlabs.com/java/java2d/strokes/
30 public class ShapeStroke implements Stroke {
31 private final Shape shapes[];
32 private final float advance;
33 //private final boolean stretchToFit = false;
34 private final boolean repeat = true;
35 private final AffineTransform t = new AffineTransform();
36 private static final float FLATNESS = 1;
38 public ShapeStroke( Shape shapes, float advance ) {
39 this( new Shape[] { shapes }, advance );
42 public ShapeStroke( Shape shapes[], float advance ) {
43 this.advance = advance;
44 this.shapes = new Shape[shapes.length];
46 for ( int i = 0; i < this.shapes.length; i++ ) {
47 Rectangle2D bounds = shapes[i].getBounds2D();
48 t.setToTranslation( -bounds.getCenterX(), -bounds.getCenterY() );
49 this.shapes[i] = t.createTransformedShape( shapes[i] );
54 public Shape createStrokedShape( Shape shape ) {
55 GeneralPath result = new GeneralPath();
56 PathIterator it = new FlatteningPathIterator( shape.getPathIterator( null ), FLATNESS );
57 float points[] = new float[6];
58 float moveX = 0, moveY = 0;
59 float lastX = 0, lastY = 0;
60 float thisX = 0, thisY = 0;
62 @SuppressWarnings("unused")
63 boolean first = false;
66 int length = shapes.length;
70 while ( currentShape < length && !it.isDone() ) {
71 type = it.currentSegment( points );
73 case PathIterator.SEG_MOVETO:
74 moveX = lastX = points[0];
75 moveY = lastY = points[1];
76 result.moveTo( moveX, moveY );
81 case PathIterator.SEG_CLOSE:
86 case PathIterator.SEG_LINETO:
89 float dx = thisX-lastX;
90 float dy = thisY-lastY;
91 float distance = (float)Math.sqrt( dx*dx + dy*dy );
92 if ( distance >= next ) {
93 float r = 1.0f/distance;
94 float angle = (float)Math.atan2( dy, dx );
95 while ( currentShape < length && distance >= next ) {
96 float x = lastX + next*dx*r;
97 float y = lastY + next*dy*r;
98 t.setToTranslation( x, y );
100 result.append( t.createTransformedShape( shapes[currentShape] ), false );
104 currentShape %= length;