gpt4 book ai didi

java - 平滑绘制的线条(类似铅笔的工具)java

转载 作者:行者123 更新时间:2023-11-30 07:09:08 24 4
gpt4 key购买 nike

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 创建一个类似铅笔的工具,但在绘制线条时遇到了一些问题。它可以正常工作,但线条非常棱角分明,一点也不平滑。

我已经研究过通过贝塞尔曲线来平滑它们,但是对于彼此接近的点来说这会很棘手。我可能只是想要某种形式的线紧挨着我拥有的线,但具有较低的 alpha 值或类似的东西。这就是我追求的效果。

现在是这个样子

http://imgur.com/dycSEwT

最佳答案

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

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 坐标配合使用)

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;
}

}

关于java - 平滑绘制的线条(类似铅笔的工具)java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23393967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com