Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a JTS-Geometry into an AWT-Shape?

Is it possible to convert a com.vividsolutions.jts.geom.Geometry (or a subclass of it) into a class that implements java.awt.Shape? Which library or method can I use to achieve that goal?

like image 891
Mnementh Avatar asked Dec 23 '22 14:12

Mnementh


1 Answers

Also have a look at ShapeWriter provided by the JTS library. I used the following code snipped to convert jts geometry objects into an awt shape.

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.vividsolutions.jts.awt.ShapeWriter;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Polygon;

public class Paint extends JPanel{
    public void paint(Graphics g) {

        Coordinate[] coords  = new Coordinate[] {new Coordinate(400, 0),  new Coordinate(200, 200),  new Coordinate(400, 400), new Coordinate(600, 200), new Coordinate(400, 0) };
        Polygon polygon = new GeometryFactory().createPolygon(coords);

        LineString ls = new GeometryFactory().createLineString(new Coordinate[] {new Coordinate(20, 20),  new Coordinate(200, 20)});

        ShapeWriter sw = new ShapeWriter();
        Shape polyShape = sw.toShape(polygon);
        Shape linShape = sw.toShape(ls);

        ((Graphics2D) g).draw(polyShape);
        ((Graphics2D) g).draw(linShape);


    }
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.getContentPane().add(new Paint());
        f.setSize(700, 700);
        f.setVisible(true);
    }
}

Edit: The result looks like this image Visualization of jts geometry objects in awt

like image 103
user3776894 Avatar answered Jan 13 '23 11:01

user3776894