平滑绘制的线条(铅笔式工具)java

时间:2014-04-30 17:00:25

标签: java graphics

if ((e != null && l.size() > 0) && (l != null)) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setStroke(new BasicStroke(2));
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        for (int i = 0; i < l.size() - 1; i++) {
            Point p1 = l.get(i);
            Point p2 = l.get(i + 1);
            g.setColor(currentColor);
            g.drawLine(p1.x, p1.y, p2.x, p2.y);
        }

        Point p3 = l.get(l.size() - 1);
        g.drawLine(p3.x, p3.y, e.getPoint().x, e.getPoint().y);
    }

我在java中创建了一个类似铅笔的工具,在绘制线条时我遇到了一些问题。它的工作原理应该如此,但线条非常边缘,并且根本不光滑。

我已经研究了通过bezier事物来平滑它们,但对于彼此接近的点来说这将是棘手的。我可能只想在我所拥有的那条线旁边使用某种形式的线,但是具有较低的α值或类似的东西。这就是我追求的效果。

这就是现在的样子。

http://imgur.com/dycSEwT

1 个答案:

答案 0 :(得分:4)

我怀疑你遇到的问题是你保留了太多的信息。你当然可以对线条做一些模糊或肥胖,这可能会帮助你创建一个更模糊,更胖的线,但我认为这实际上不会帮助你清理紧张。我建议线条看起来非常好,这将是一个两步的过程。第一个过程是使用DP Line简化来消除许多轻微的抖动。该过程的第二步是使用Centripetal Catmull-Rom样条曲线,以使整条线条像非常优雅的曲线一样流动。为此目的使用这种样条曲线的美妙之处在于,您不需要做任何认真的工作,试图弄清楚如何提出用于做Besier曲线的所有控制点。你可以在曲线的起点和终点使用原点和两点。

Duglas-Peucker线条简化器可以在Java中使用JTS从生动的解决方案中获得: http://www.vividsolutions.com/jts/JTSHome.htm

这是Catmull-Rom代码的链接。 Catmull-rom curve with no cusps and no self-intersections

直接绘图(紧张不安)

Direct

简化绘图(使用JTS DP线简化)

Simple (just doing DP Line Simplification)

使用Centripetal Catmull-Rom进行简化和平滑

DP + Centripetal Catmull-Rom

绘制面板示例代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package demo;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hdunsford
 */
public class DrawPanel extends javax.swing.JPanel {

    private List<Coordinate> coords;

    /**
     * Creates new form DrawPanel
     */
    public DrawPanel() {
        initComponents();
        coords = new ArrayList<>();

        this.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseDragged(MouseEvent e) {
                coords.add(new Coordinate(e.getX(), e.getY()));
                repaint();
            }

            @Override
            public void mouseMoved(MouseEvent e) {

            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        try {
            super.paintComponent(g); // paint background
            Graphics2D g2d = (Graphics2D) g;
            g2d.setStroke(new BasicStroke(2));
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            GeometryFactory f = new GeometryFactory();

            if (coords.size() < 2) {
                return;
            }
            LineString ls = f.createLineString(coords.toArray(new Coordinate[0]));
            //Geometry simple = ls;
            Geometry simple = DouglasPeuckerSimplifier.simplify(ls, 3.0);
            if (simple.getCoordinates().length < 2) {
                return;
            }
            List<Coordinate> raw = new ArrayList<>();
            raw.addAll(Arrays.asList(simple.getCoordinates()));
            List<Coordinate> spline = CatmullRom.interpolate(raw, 10);

            int[] xPoints = new int[spline.size()];
            int[] yPoints = new int[spline.size()];
            for (int i = 0; i < spline.size(); i++) {
                xPoints[i] = (int) spline.get(i).x;
                yPoints[i] = (int) spline.get(i).y;
            }

            g2d.setColor(Color.red);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawPolyline(xPoints, yPoints, xPoints.length);
        } catch (Exception ex) {
            Logger.getLogger(DrawPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING:
     * Do NOT modify this code. The content of this method is always regenerated by the
     * Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

Centripetal Catmull-Rom(调整为与JTS Coordinate合作)

package demo;

import com.vividsolutions.jts.geom.Coordinate;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author hdunsford
 */
public class CatmullRom {

    /**
     * This method will calculate the Catmull-Rom interpolation curve, returning it as a
     * list of Coordinate coordinate objects. This method in particular adds the first and
     * last control points which are not visible, but required for calculating the spline.
     *
     * @param coordinates The list of original straight line points to calculate an
     * interpolation from.
     * @param pointsPerSegment The integer number of equally spaced points to return along
     * each curve. The actual distance between each point will depend on the spacing
     * between the control points.
     * @return The list of interpolated coordinates.
     */
    public static List<Coordinate> interpolate(List<Coordinate> coordinates, int pointsPerSegment)
            throws Exception {
        List<Coordinate> vertices = new ArrayList<>();
        for (Coordinate c : coordinates) {
            vertices.add(new Coordinate(c.x, c.y));
        }
        if (pointsPerSegment < 2) {
            throw new Exception("The pointsPerSegment parameter must be greater than 2, since 2 points is just the linear segment.");
        }

        // Cannot interpolate curves given only two points.  Two points
        // is best represented as a simple line segment.
        if (vertices.size() < 3) {
            return vertices;
        }

        // Test whether the shape is open or closed by checking to see if
        // the first point intersects with the last point.  M and Z are ignored.
        boolean isClosed = vertices.get(0).x == vertices.get(vertices.size() - 1).x
                && vertices.get(0).y == vertices.get(vertices.size() - 1).y;
        if (isClosed) {
            // Use the second and second from last points as control points.
            // get the second point.
            Coordinate p2 = new Coordinate(vertices.get(1));
            // get the point before the last point
            Coordinate pn1 = new Coordinate(vertices.get(vertices.size() - 2));

            // insert the second from the last point as the first point in the list
            // because when the shape is closed it keeps wrapping around to
            // the second point.
            vertices.add(0, pn1);
            // add the second point to the end.
            vertices.add(p2);
        } else {
        // The shape is open, so use control points that simply extend
            // the first and last segments

            // Get the change in x and y between the first and second coordinates.
            double dx = vertices.get(1).x - vertices.get(0).x;
            double dy = vertices.get(1).y - vertices.get(0).y;

            // Then using the change, extrapolate backwards to find a control point.
            double x1 = vertices.get(0).x - dx;
            double y1 = vertices.get(0).y - dy;

            // Actaully create the start point from the extrapolated values.
            Coordinate start = new Coordinate(x1, y1);

            // Repeat for the end control point.
            int n = vertices.size() - 1;
            dx = vertices.get(n).x - vertices.get(n - 1).x;
            dy = vertices.get(n).y - vertices.get(n - 1).y;
            double xn = vertices.get(n).x + dx;
            double yn = vertices.get(n).y + dy;
            Coordinate end = new Coordinate(xn, yn);

            // insert the start control point at the start of the vertices list.
            vertices.add(0, start);

            // append the end control ponit to the end of the vertices list.
            vertices.add(end);
        }

        // Dimension a result list of coordinates. 
        List<Coordinate> result = new ArrayList<>();
        // When looping, remember that each cycle requires 4 points, starting
        // with i and ending with i+3.  So we don't loop through all the points.
        for (int i = 0; i < vertices.size() - 3; i++) {

            // Actually calculate the Catmull-Rom curve for one segment.
            List<Coordinate> points = interpolate(vertices, i, pointsPerSegment);
            // Since the middle points are added twice, once for each bordering
            // segment, we only add the 0 index result point for the first
            // segment.  Otherwise we will have duplicate points.
            if (result.size() > 0) {
                points.remove(0);
            }

            // Add the coordinates for the segment to the result list.
            result.addAll(points);
        }
        return result;

    }

    /**
     * Given a list of control points, this will create a list of pointsPerSegment points
     * spaced uniformly along the resulting Catmull-Rom curve.
     *
     * @param points The list of control points, leading and ending with a coordinate that
     * is only used for controling the spline and is not visualized.
     * @param index The index of control point p0, where p0, p1, p2, and p3 are used in
     * order to create a curve between p1 and p2.
     * @param pointsPerSegment The total number of uniformly spaced interpolated points to
     * calculate for each segment. The larger this number, the smoother the resulting
     * curve.
     * @return the list of coordinates that define the CatmullRom curve between the points
     * defined by index+1 and index+2.
     */
    public static List<Coordinate> interpolate(List<Coordinate> points, int index, int pointsPerSegment) {
        List<Coordinate> result = new ArrayList<>();
        double[] x = new double[4];
        double[] y = new double[4];
        double[] time = new double[4];
        for (int i = 0; i < 4; i++) {
            x[i] = points.get(index + i).x;
            y[i] = points.get(index + i).y;
            time[i] = i;
        }

        double tstart;
        double tend;
        double total = 0;
        for (int i = 1; i < 4; i++) {
            double dx = x[i] - x[i - 1];
            double dy = y[i] - y[i - 1];
            total += Math.pow(dx * dx + dy * dy, .25);
            time[i] = total;
        }
        tstart = time[1];
        tend = time[2];

        int segments = pointsPerSegment - 1;
        result.add(points.get(index + 1));
        for (int i = 1; i < segments; i++) {
            double xi = interpolate(x, time, tstart + (i * (tend - tstart)) / segments);
            double yi = interpolate(y, time, tstart + (i * (tend - tstart)) / segments);
            result.add(new Coordinate(xi, yi));
        }
        result.add(points.get(index + 2));
        return result;
    }

    /**
     * Unlike the other implementation here, which uses the default "uniform" treatment of
     * t, this computation is used to calculate the same values but introduces the ability
     * to "parameterize" the t values used in the calculation. This is based on Figure 3
     * from http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
     *
     * @param p An array of double values of length 4, where interpolation occurs from p1
     * to p2.
     * @param time An array of time measures of length 4, corresponding to each p value.
     * @param t the actual interpolation ratio from 0 to 1 representing the position
     * between p1 and p2 to interpolate the value.
     * @return
     */
    public static double interpolate(double[] p, double[] time, double t) {
        double L01 = p[0] * (time[1] - t) / (time[1] - time[0]) + p[1] * (t - time[0]) / (time[1] - time[0]);
        double L12 = p[1] * (time[2] - t) / (time[2] - time[1]) + p[2] * (t - time[1]) / (time[2] - time[1]);
        double L23 = p[2] * (time[3] - t) / (time[3] - time[2]) + p[3] * (t - time[2]) / (time[3] - time[2]);
        double L012 = L01 * (time[2] - t) / (time[2] - time[0]) + L12 * (t - time[0]) / (time[2] - time[0]);
        double L123 = L12 * (time[3] - t) / (time[3] - time[1]) + L23 * (t - time[1]) / (time[3] - time[1]);
        double C12 = L012 * (time[2] - t) / (time[2] - time[1]) + L123 * (t - time[1]) / (time[2] - time[1]);
        return C12;
    }

}