java JavaFX Canvas 绘制具有透明度的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28100060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:59:30  来源:igfitidea点击:

JavaFX Canvas draw image with transparency

javajavafx

提问by Voldemort

With a JavaFX Canvas, you can use drawImage(). However, is there anyway to draw the image with transparency (draw it with only 50% of opacity) or tint it with color?

使用 JavaFX 画布,您可以使用drawImage(). 但是,无论如何要绘制具有透明度的图像(仅以 50% 的不透明度绘制)或用颜色对其进行着色?

回答by jewelsea

Methods to Control Canvas Draw Operations

控制画布绘制操作的方法

There are methods to control the attributes of draw canvas drawing operations:

有一些方法可以控制绘制画布绘制操作的属性:

Sample Usage

示例用法

batsignal

蝙蝠信号

The source image used by the program is:

程序使用的源图像为:

bat signal

蝙蝠信号

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.effect.*;
import javafx.scene.image.Image;
import javafx.scene.paint.*;
import javafx.stage.Stage;

public class CanvasEffects extends Application {

    @Override
    public void start(Stage stage) {
        final Image image = new Image(IMAGE_LOC);

        final int NUM_IMGS = 5;
        final double W = image.getWidth();
        final double H = image.getHeight();

        final Canvas canvas = new Canvas(W * NUM_IMGS, H);
        final GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFill(Color.GOLD);
        gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());

        gc.setGlobalBlendMode(BlendMode.SCREEN);

        for (int i = 0 ; i < NUM_IMGS; i++) {
            final double opacity = 1 - ((double) i) / NUM_IMGS;
            System.out.println(opacity);
            gc.setGlobalAlpha(opacity);
            gc.setEffect(new BoxBlur(i * 2, i * 2, 3));

            gc.drawImage(image, i * W, 0);
        }

        stage.setScene(new Scene(new Group(canvas)));
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

    // icon license: Linkware (Backlink to http://uiconstock.com required) commercial usage not allowed.
    private static final String IMAGE_LOC = "http://icons.iconarchive.com/icons/uiconstock/flat-halloween/128/Halloween-Bat-icon.png";
}