下面的可运行示例中的箭头应分别用红色的alpha渐变填充,从箭头的底部到其头部。
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.stage.Stage;
public class JavaFXAlphaGradient extends Application {
public static void main(String... args) {
Application.launch(JavaFXAlphaGradient.class, args);
}
@Override
public void start(Stage primaryStage) throws Exception {
double size = 600.0;
BorderPane pane = new BorderPane();
Canvas canvas = new Canvas();
pane.getChildren().add(canvas);
canvas.setHeight(size);
canvas.setWidth(size);
Point2D midPoint = new Point2D(canvas.getWidth() / 2, canvas.getHeight() / 2);
Point2D topLeft = new Point2D(0.0, 0.0);
Point2D topRight = new Point2D(canvas.getWidth(), 0.0);
Point2D bottomLeft = new Point2D(0.0, canvas.getHeight());
Point2D bottomRight = new Point2D(canvas.getWidth(), canvas.getHeight());
drawArrow(canvas, midPoint, topLeft);
drawArrow(canvas, midPoint, topRight);
drawArrow(canvas, midPoint, bottomLeft);
drawArrow(canvas, midPoint, bottomRight);
Scene scene = new Scene(pane, size, size);
primaryStage.setScene(scene);
primaryStage.show();
}
private void drawArrow(Canvas canvas, Point2D from, Point2D to) {
GraphicsContext gc = canvas.getGraphicsContext2D();
double distance = from.distance(to);
double arrowWidth = 30.0;
double arrowheadSide = 30.0;
gc.save();
Point2D rotationPoint = new Point2D((from.getX() + to.getX()) / 2, (from.getY() + to.getY()) / 2);
gc.translate(rotationPoint.getX(), rotationPoint.getY());
double theta = Math.atan2(from.getY() - to.getY(), from.getX() - to.getX());
gc.rotate(180 + Math.toDegrees(theta));
gc.beginPath();
gc.moveTo(-distance / 2, arrowWidth / 2);
gc.lineTo(distance / 2 - arrowWidth, arrowWidth / 2);
gc.lineTo(distance / 2 - arrowWidth, arrowWidth / 2);
gc.lineTo(distance / 2, 0.0);
gc.lineTo(distance / 2 - arrowWidth, -arrowheadSide / 2);
gc.lineTo(distance / 2 - arrowWidth, -arrowWidth / 2);
gc.lineTo(-distance / 2, -arrowWidth / 2);
gc.closePath();
Color red03 = new Color(1.0, 0.0, 0.0, 0.3);
Color red08 = new Color(1.0, 0.0, 0.0, 0.8);
// I want an alpha gradient for each arrow from "from" to "to" - this doesn't work though
gc.setFill(new LinearGradient(from.getX(), from.getY(), to.getX(), to.getY(), true,
CycleMethod.NO_CYCLE, new Stop(0.0, red03), new Stop(1.0, red08)));
gc.fill();
gc.restore();
}
}
我肯定想念一些明显的东西!
感谢您的关注!
Stackoverflow希望我添加更多细节,因为“主要是代码”,但我真的不知道要添加什么。 :-)
最佳答案
弄清楚了-对不起,我完全误读了有关比例变量的文档。
gc.setFill(new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE,
new Stop(0.0, red03), new Stop(1.0, red08)));