我在 ImageView 中有一张图像。我想做的就是给它添加颜色。基本上它就像图像上的一层颜色。所以我尝试使用 ColorPicker 为 T 恤图像添加颜色,但我不知道如何做到这一点。我已经尝试过将其与 colorAdjust 类一起使用,但它在 T 恤上提供的颜色与我从 ColorPicker 中选择的颜色不同。
顺便说一句,我正在使用 SceneBuilder。
图形用户界面
T恤
@FXML
private void changecolor(ActionEvent event) {
Color mycolor=mycolorpicker.getValue();
label.setBackground(new Background(new BackgroundFill(mycolor,null,null)));
Image img=new Image(getClass().getResourceAsStream("tshirt7.PNG"));
imageV.setImage(img);
ColorAdjust colorAdjust = new ColorAdjust();
colorAdjust.setHue((mycolor.getHue()/360));
colorAdjust.setSaturation(mycolor.getSaturation());
colorAdjust.setBrightness(mycolor.getBrightness()-1);
imageV.setEffect(colorAdjust);
}
我期望图像上的颜色与我从 ColorPicker 中选择的颜色相同。但 T 恤上的颜色不准确。
最佳答案
如何从颜色选择器为图像着色。
- 确保您的
png
输入图像具有适当的透明颜色区域(您的示例 T 恤图像就有)。 - 定义 ColorPicker选择你的颜色。
- 绑定(bind) picked color到 MULTIPLY blended ColorInput对 desaturated 的影响单色adjusted或grayscaled图像,图像 clipped由图像定义的剪辑。
更多信息请参见:
示例
将使用的图像(我使用了您问题中提供的图像)放置在与放置示例代码的包具有相同目录结构的资源文件夹中。
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.effect.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Objects;
public class TShirtDesigner extends Application {
@Override
public void start(Stage stage) throws Exception {
ColorPicker colorPicker = new ColorPicker();
Image tshirtImage = new Image(
Objects.requireNonNull(
TShirtDesigner.class.getResource(
"tshirt.png"
)
).toExternalForm()
);
ImageView tshirt = new ImageView(tshirtImage);
tshirt.setClip(new ImageView(tshirtImage));
bindImageColor(
tshirt,
colorPicker.valueProperty()
);
VBox layout = new VBox(
10,
colorPicker,
tshirt
);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(10));
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
private static void bindImageColor(
ImageView imageView,
ObjectProperty<Color> colorProperty
) {
ColorInput colorInput = new ColorInput(
0,
0,
imageView.getImage().getWidth(),
imageView.getImage().getHeight(),
colorProperty.get()
);
colorInput.paintProperty().bind(
colorProperty
);
ColorAdjust monochrome = new ColorAdjust();
monochrome.setSaturation(-1.0);
Blend colorBlend = new Blend(
BlendMode.MULTIPLY,
monochrome,
colorInput
);
imageView.setEffect(colorBlend);
}
public static void main(String[] args) {
launch(args);
}
}
关于java - 在 JavaFX 中的图像上使用 ColorPicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76626020/