如何剪辑Path2D?

时间:2011-02-16 15:17:44

标签: java java-2d

有没有办法将Path2D剪辑到某个区域/其他path2D实例?

简单示例(我正在寻找能够在一般情况下工作的东西,其中路径可能包括四边形或立方体,可能是也可能不是单数):

我有一个线段(0,10) - > (30,10)我想在三角形(10,0),(20,20),(20,0)内剪切,理想地产生线段(15,10) - > (20,10)

我可以使用“new Area(Shape);”将Path2D转换为某个区域然后使用“Area.intersect(area)”进行剪辑,但如果路径未闭合,则会返回空白区域。

我可以使用“Graphics2D.clip(Shape)”剪辑绘图区域,但我希望得到返回的形状(在某些情况下,我希望在实际渲染之前进行进一步的操作)

在搜索API文档后,我发现无法直接执行此操作。我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

无法使用Area剪切路径的原因是Path2D对象的区域为零。路径的宽度未定义。 Area类严格用于具有区域的对象。

您可以剪裁图形,因为您已经定义了笔划宽度,用于定义路径区域。

因此,如果要剪切路径,则需要使用Stroke.createStrokedShape(Shape)从路径创建描边形状

以下是一个例子:

public static void main(String[] args) throws IOException {

    String imgFormat = "PNG";

    Path2D path = new Path2D.Double();
    BasicStroke pathStroke = 
        new BasicStroke( 2 );


    // Create the path to be clipped:       
    int pathPoints[] = { 0, 10, 30, 10 };
    path.moveTo( pathPoints[ 0 ], pathPoints[1] );
    for( int i = 2; i < pathPoints.length; i+=2 ) {
        path.lineTo( pathPoints[ i ], pathPoints[ i+1 ] );
    }
    // Create the shape representing the clip area
    Polygon clipShape = new Polygon();
    int triPoints[] = { 10, 0, 20, 20, 20, 0 };
    for( int i = 0; i < triPoints.length; i+=2 ) {
        clipShape.addPoint( triPoints[i], triPoints[i+1] );
    }
    // Create the path with area using the stroke
    Shape clippedPath = pathStroke.createStrokedShape( path );

    // Apply a scale so the image is easier to see
    int scale = 10;
    AffineTransform at = AffineTransform.getScaleInstance( scale, scale );
    Shape sPath = at.createTransformedShape( path );
    Shape sClip = at.createTransformedShape( clipShape );

    // Create the Area shape that represents the path that is clipped by the clipShape
    Area clipArea = new Area( sClip );
    clipArea.intersect( new Area( at.createTransformedShape( clippedPath ) ) );


    int bbox = 10;
    Rectangle rect = sPath.getBounds();
    rect.add( sClip.getBounds() );
    // Expand the drawing area      
    rect.width += bbox;
    rect.height += bbox;
    rect.x -= bbox/2;
    rect.y -= bbox/2;
    BufferedImage img = new BufferedImage( rect.width, rect.height, BufferedImage.TYPE_INT_ARGB  );
    Graphics2D g2 = img.createGraphics();

    g2.setStroke( pathStroke );
    g2.setColor( Color.black );
    g2.draw( sPath );

    g2.setColor( Color.red );
    g2.draw( sClip );

    g2.setColor( Color.green );
    g2.draw( clipArea );

    g2.finalize();

    File img1 = new File( "/tmp/img1.png" );
    ImageIO.write( img, imgFormat, img1 );
}