Java Code Examples for javafx.scene.canvas.GraphicsContext#drawImage()

The following examples show how to use javafx.scene.canvas.GraphicsContext#drawImage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TileImage.java    From mcaselector with MIT License 6 votes vote down vote up
public static void draw(Tile tile, GraphicsContext ctx, float scale, Point2f offset) {
	if (tile.image != null) {
		ctx.drawImage(tile.getImage(), offset.getX(), offset.getY(), Tile.SIZE / scale, Tile.SIZE / scale);
	} else {
		ctx.drawImage(ImageHelper.getEmptyTileImage(), offset.getX(), offset.getY(), Tile.SIZE / scale, Tile.SIZE / scale);
	}

	if (tile.marked) {
		//draw marked region
		ctx.setFill(Config.getRegionSelectionColor().makeJavaFXColor());
		ctx.fillRect(offset.getX(), offset.getY(), Tile.SIZE / scale, Tile.SIZE / scale);
	} else if (tile.markedChunks.size() > 0) {

		if (tile.markedChunksImage == null) {
			createMarkedChunksImage(tile, Tile.getZoomLevel(scale));
		}

		// apply markedChunksImage to ctx
		ctx.drawImage(tile.markedChunksImage, offset.getX(), offset.getY(), Tile.SIZE / scale, Tile.SIZE / scale);
	}
}
 
Example 2
Source File: Renderer.java    From Aidos with GNU General Public License v3.0 6 votes vote down vote up
public static void playAnimation(GraphicsContext gc, double time, int actualSize, int startingPointX, int startingPointY, int numberOfFrames, int x, int y, double width, double height, double scale, boolean reversePlay, double playSpeed) {

        double speed = playSpeed >= 0 ? playSpeed : 0.3;

        // index reporesents the index of image to be drawn from the set of images representing frames of animation
        int index = findCurrentFrame(time, numberOfFrames, speed);

        // newX represents the X coardinate of image in the spritesheet image to be drawn on screen
        int newSpriteSheetX = reversePlay ? startingPointX + index * actualSize : startingPointX;
        // newY represents the X coardinate of image in the spritesheet image to be drawn on screen
        int newSpriteSheetY = reversePlay ? startingPointY : startingPointY + index * actualSize;
        //System.out.println("Time, Total Frames" + time + ", " + numberOfFrames);
        //System.out.println("index=" + index + " newSpriteSheetX=" + newSpriteSheetX + " newSpriteSheetY=" + newSpriteSheetY + " width=" + width + " height=" + height + " x=" + x + " y=" + y + " width=" + width * scale + " height=" + height * scale);
                    //img,             sx,              sy,     w,     h,  dx, dy,        dw,             dh
        gc.drawImage(img, newSpriteSheetX, newSpriteSheetY, width, height, x, y, width * scale, height * scale);
    }
 
Example 3
Source File: ShipImage.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * 画像レイヤーを適用します
 *
 * @param gc GraphicsContext
 * @param layers 画像レイヤー
 */
private static void applyLayers(GraphicsContext gc, List<Layer> layers) {
    for (Layer layer : layers) {
        Image img = null;
        if (layer.path != null) {
            Path p = Paths.get(AppConfig.get().getResourcesDir()).resolve(layer.path);
            img = COMMON_CACHE.get(p.toUri().toString(), (url, status) -> {
                Image image = new Image(url);
                status.setDoCache(!image.isError());
                return image;
            });
        }
        if (layer.img != null) {
            img = layer.img;
        }
        if (img != null) {
            if (layer.w > 0) {
                gc.drawImage(img, layer.x, layer.y, layer.w, layer.h);
            } else {
                gc.drawImage(img, layer.x, layer.y);
            }
        }
    }
}
 
Example 4
Source File: ComboRenderer.java    From arma-dialog-creator with MIT License 5 votes vote down vote up
private void paintArrow(GraphicsContext gc, ImageOrTextureHelper helper) {
	final int arrowWidth = getHeight();
	final int arrowHeight = arrowWidth;
	final int arrowX = x2 - arrowWidth;
	final int arrowY = y1;

	switch (helper.getMode()) {
		case Image: {
			gc.drawImage(helper.getImage(), arrowX, arrowY, arrowWidth, arrowHeight);
			break;
		}
		case LoadingImage: {
			break;
		}
		case Texture: {
			TexturePainter.paint(gc, helper.getTexture(), arrowX, arrowY, arrowX + arrowWidth, arrowY + arrowHeight);
			break;
		}
		case TextureError: {
			paintTextureError(gc, arrowX, arrowY, arrowWidth, arrowHeight);
			break;
		}
		case ImageError: {
			paintImageError(gc, arrowX, arrowY, arrowWidth, arrowHeight);
			break;
		}
		default:
			throw new IllegalStateException("unknown mode:" + arrowFull_combo.getMode());
	}
}
 
Example 5
Source File: WTKTiledMap.java    From javafx-TKMapEditor with GNU General Public License v3.0 5 votes vote down vote up
public void draw(GraphicsContext gContext2D) {
	if (isLoadFinished) {
		// 绘制多图层地图
		int length = mapLayerList.size();
		int tileWidth = WTKMap.getInstance().getTileWidth();
		int tileHeight = WTKMap.getInstance().getTileHeight();
		if (length > 0) {
			for (int i = length - 1; i >= 0; i--) {
				WTKLayer mapLayer = mapLayerList.get(i);
				if (mapLayer.isVisible()) {
					WTKMapTile[][] tiles = mapLayer.getMapTiles();
					gContext2D.setGlobalAlpha(mapLayer.getAlpha());
					if (tiles != null) {
						for (int y = 0; y < tiles.length; y++) {
							for (int x = 0; x < tiles[0].length; x++) {
								if (tiles[y][x] != null) {
									AltasResource resource = WAltasResourceManager.getInstance().getResourceById(
											tiles[y][x].getAltasId());
									if (resource != null) {
										Image image = resource.getImage();
										int index = tiles[y][x].getAltasIndex();
										if (index != -1) {
											int cellX = (int) (image.getWidth() / tileWidth);
											int col = index % cellX;
											int row = index / cellX;
											gContext2D.drawImage(image, col * tileWidth, row * tileHeight,
													tileWidth, tileHeight, getX() + x * tileWidth, getY() + y
															* tileHeight, tileWidth, tileHeight);
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
}
 
Example 6
Source File: Example2.java    From Introduction-to-JavaFX-for-Game-Development with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void start(Stage theStage) 
{
    theStage.setTitle( "Canvas Example" );
    
    Group root = new Group();
    Scene theScene = new Scene( root );
    theStage.setScene( theScene );
    
    Canvas canvas = new Canvas( 400, 200 );
    root.getChildren().add( canvas );
    
    GraphicsContext gc = canvas.getGraphicsContext2D();
    
    gc.setFill( Color.RED );
    gc.setStroke( Color.BLACK );
    gc.setLineWidth(2);
    Font theFont = Font.font( "Times New Roman", FontWeight.BOLD, 48 );
    gc.setFont( theFont );
    gc.fillText( "Hello, World!", 60, 50 );
    gc.strokeText( "Hello, World!", 60, 50 );
    
    Image earth = new Image( "earth.png" );
    gc.drawImage( earth, 180, 100 );
    
    theStage.show();
}
 
Example 7
Source File: DragAndDropHandler.java    From FxDock with Apache License 2.0 5 votes vote down vote up
protected static Image createDragImage(FxDockPane client)
{
	SnapshotParameters sp = new SnapshotParameters();
	sp.setFill(Color.TRANSPARENT);
	
	WritableImage im = client.snapshot(sp, null);

	if(client.isPaneMode())
	{
		return im;
	}
	
	// include selected tab
	FxDockTabPane tp = (FxDockTabPane)DockTools.getParent(client);
	Node n = tp.lookup(".tab:selected");
	WritableImage tim = n.snapshot(sp, null);
	
	double dy = tim.getHeight();
	
	// must adjust for the tab
	deltay += dy;
	
	double w = Math.max(im.getWidth(), tim.getWidth());
	double h = im.getHeight() + dy;
	Canvas c = new Canvas(w, h);
	GraphicsContext g = c.getGraphicsContext2D();
	g.drawImage(tim, 0, 0);
	g.drawImage(im, 0, dy);
	return c.snapshot(sp, null);
}
 
Example 8
Source File: Text.java    From CircuitSim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void paint(GraphicsContext graphics, CircuitState state) {
	graphics.setFill(Color.BLACK);
	graphics.setStroke(Color.BLACK);
	
	graphics.setLineWidth(2);
	
	int x = getScreenX();
	int y = getScreenY();
	int width = getScreenWidth();
	int height = getScreenHeight();
	
	if(text.isEmpty()) {
		graphics.drawImage(textImage, x, y, width, height);
	} else {
		graphics.setFont(GuiUtils.getFont(13));
		for(int i = 0; i < lines.size(); i++) {
			String line = lines.get(i);
			Bounds bounds = GuiUtils.getBounds(graphics.getFont(), line, false);
			
			graphics.fillText(line,
			                  x + (width - bounds.getWidth()) * 0.5,
			                  y + 15 * (i + 1));
			
			if(entered && i == lines.size() - 1) {
				double lx = x + (width + bounds.getWidth()) * 0.5 + 3;
				double ly = y + 15 * (i + 1);
				graphics.strokeLine(lx, ly - 10, lx, ly);
			}
		}
	}
}
 
Example 9
Source File: FxNinePatch.java    From NinePatch with Apache License 2.0 5 votes vote down vote up
@Override
public void drawImage(GraphicsContext g2d,
                      Image image,
                      int sx,
                      int sy,
                      int sw,
                      int sh,
                      int dx,
                      int dy,
                      int dw,
                      int dh)
{
    g2d.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
}
 
Example 10
Source File: ShortcutButtonRenderer.java    From arma-dialog-creator with MIT License 5 votes vote down vote up
private void paintShortcutThing(GraphicsContext gc) {
	final int controlWidth = getWidth();
	final int controlHeight = getHeight();

	int x1 = (int) (this.x1 + Math.round(controlWidth * shortcutPos_left));
	int y1 = (int) (this.y1 + Math.round(controlHeight * shortcutPos_top));
	int x2 = (int) (this.x1 + Math.round(controlWidth * shortcutPos_w));
	int y2 = (int) (this.y1 + Math.round(controlHeight * shortcutPos_h));
	if (textureNoShortcut.getValue() != null && textureNoShortcut.getValue().toString().length() == 0) {
		//ignore the texture if defined but no text is entered
		return;
	}
	switch (textureNoShortcut.getMode()) {
		case Image: {
			gc.drawImage(textureNoShortcut.getImage(), x1, y1, x2 - x1, y2 - y1);
			break;
		}
		case ImageError: {
			paintImageError(gc, x1, y1, 30, 30);
			break;
		}
		case LoadingImage: {
			break;
		}
		case Texture: {
			TexturePainter.paint(gc, textureNoShortcut.getTexture(), x1, y1, x2, y2);
			break;
		}
		case TextureError: {
			paintTextureError(gc, x1, y1, x2 - x1, y2 - y1);
			break;
		}
	}
}
 
Example 11
Source File: ContourDataSetRenderer.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
private void drawHeatMap(final GraphicsContext gc, final ContourDataSetCache lCache) {
    final long start = ProcessingProfiler.getTimeStamp();

    // N.B. works only since OpenJFX 12!! fall-back for JDK8 is the old implementation
    gc.setImageSmoothing(isSmooth());

    // process z quantisation to colour transform
    final WritableImage image = localCache.convertDataArrayToImage(lCache.reduced, lCache.xSize, lCache.ySize, getColorGradient());
    ProcessingProfiler.getTimeDiff(start, "color map");

    gc.drawImage(image, lCache.xDataPixelMin, lCache.yDataPixelMin, lCache.xDataPixelRange, lCache.yDataPixelRange);

    localCache.add(image);
    ProcessingProfiler.getTimeDiff(start, "drawHeatMap");
}
 
Example 12
Source File: MiscHelpers.java    From arma-dialog-creator with MIT License 5 votes vote down vote up
public static void paintRotatedImage(@NotNull GraphicsContext gc, @NotNull Image img, int x, int y, int w, int h, double rotateDeg) {
	gc.save();
	gc.translate(x + w / 2, y + h / 2); //move to center
	gc.rotate(rotateDeg);
	gc.drawImage(img, -w / 2, -h / 2, w, h);
	gc.restore();
}
 
Example 13
Source File: Renderer.java    From Aidos with GNU General Public License v3.0 5 votes vote down vote up
public static void playAnimation(Image[] imgs, double speed, int x, int y, double w, double h) {
    double time = GameLoop.getCurrentGameTime();
    GraphicsContext gc = Sandbox.getGraphicsContext();
    int numberOfFrames = imgs.length;
    int index = findCurrentFrame(time, numberOfFrames, speed);
    //System.out.println("index= "+index+" x="+x+" y="+y+" w="+w+" h="+h+" no of frames="+imgs.length+" speed="+speed+" time="+time);
    gc.drawImage(imgs[index], x, y, w, h);
}
 
Example 14
Source File: FxmlImageManufacture.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static Image addArcFx2(Image image, int arc, Color bgColor) {
        try {
            if (image == null || arc <= 0) {
                return null;
            }

            double imageWidth = image.getWidth(), imageHeight = image.getHeight();

            final Canvas canvas = new Canvas(imageWidth, imageHeight);
            final GraphicsContext g = canvas.getGraphicsContext2D();
            g.setGlobalBlendMode(BlendMode.ADD);
            g.setFill(bgColor);
            g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
            g.drawImage(image, 0, 0);

            Rectangle clip = new Rectangle(imageWidth, imageHeight);
            clip.setArcWidth(arc);
            clip.setArcHeight(arc);
            canvas.setClip(clip);
            SnapshotParameters parameters = new SnapshotParameters();
            parameters.setFill(Color.TRANSPARENT);
            WritableImage newImage = canvas.snapshot(parameters, null);
            return newImage;

        } catch (Exception e) {
//            logger.error(e.toString());
            return null;
        }

    }
 
Example 15
Source File: ShipImage.java    From logbook-kai with MIT License 5 votes vote down vote up
/**
 * HPゲージ
 * @param chara キャラクター
 * @param canvas Canvas
 * @param gc GraphicsContext
 */
private static void writeHpGauge(Chara chara, Canvas canvas, GraphicsContext gc) {
    double w = canvas.getWidth();
    double h = canvas.getHeight();
    double gaugeWidth = 7;
    double hpPer = (double) chara.getNowhp() / (double) chara.getMaxhp();
    gc.drawImage(createGauge(gaugeWidth, h, hpPer, ShipImage::hpGaugeColor, HPGAUGE_CACHE), w - gaugeWidth, 0);
}
 
Example 16
Source File: ShortcutButtonRenderer.java    From arma-dialog-creator with MIT License 4 votes vote down vote up
@Override
public void paint(@NotNull GraphicsContext gc, CanvasContext canvasContext) {
	boolean preview = paintPreview(canvasContext);

	final int controlWidth = getWidth();
	final int controlHeight = getHeight();
	ImageOrTextureHelper bgTexture = animTextureNormal;

	int textPosX = x1 + (int) (Math.round(controlWidth * textPos_left));
	int textPosY = y1 + (int) (Math.round(controlHeight * textPos_top));

	if (preview) {
		if (isEnabled()) {
			blinkControlHandler.paint(gc);
		}

		double ratio = focusedColorAlternator.updateAndGetRatio();
		Color colorBackground = this.backgroundColor;
		Color color = textRenderer.getTextColor();

		if (!isEnabled()) {
			//button is disabled
			bgTexture = animTextureDisabled;
			textRenderer.setTextColor(colorDisabled);
		} else if (mouseButtonDown == MouseButton.PRIMARY) {
			//button is being clicked
			bgTexture = animTexturePressed;
			//background color remains as "colorBackground" property value
			//text color remains as "color" property value
		} else if (mouseOver) {
			//mouse is over the button
			bgTexture = animTextureOver;
			//interpolate "color" with "colorFocused"
			if (periodOverMillis > 0) {
				textRenderer.setTextColor(colorFocused.interpolate(color2, ratio));
				setBackgroundColor(colorBackgroundFocused.interpolate(colorBackground2, ratio));
			}
			//interpolate "colorBackgroundFocused" with "colorBackground2"
			focusedColorAlternator.setAlternateMillis(periodOverMillis);
		} else if (focused) {
			bgTexture = animTextureFocused;
			if (periodFocusMillis > 0) {
				textRenderer.setTextColor(color2.interpolate(colorFocused, ratio));
				setBackgroundColor(colorBackground2.interpolate(colorBackgroundFocused, ratio));
			}
			focusedColorAlternator.setAlternateMillis(periodFocusMillis);
		}

		//paint the background texture/image
		switch (bgTexture.getMode()) {
			case Image: {
				// In arma 3, they do some weird as shit for manipulating the background texture.
				// Currently (July 2017), I don't know how they are doing it. So, I'll just stretch the image to
				// width of the control.
				Image image = bgTexture.getImage();
				if (image == null) {
					throw new IllegalStateException();
				}
				gc.drawImage(image, x1, y1, controlWidth, controlHeight);

				gc.setGlobalBlendMode(BlendMode.MULTIPLY);
				super.paint(gc, canvasContext);
				gc.setGlobalBlendMode(BlendMode.SRC_OVER);
				break;
			}
			case ImageError: {
				paintImageError(gc, x1, y1, controlWidth, controlHeight);
				break;
			}
			case LoadingImage: {
				super.paint(gc, canvasContext);
				break;
			}
			case Texture: {
				TexturePainter.paint(gc, bgTexture.getTexture(), backgroundColor, x1, y1, x2, y2);
				break;
			}
			case TextureError: {
				paintTextureError(gc, x1, y1, controlWidth, controlHeight);
				break;
			}
		}

		paintShortcutThing(gc);

		textRenderer.paint(gc, textPosX, textPosY);

		//reset the colors again
		setBackgroundColor(colorBackground);
		textRenderer.setTextColor(color);

		if (this.mouseOver) {
			canvasContext.paintLast(tooltipRenderFunc);
		}
	} else {
		super.paint(gc, canvasContext);
		paintShortcutThing(gc);
		textRenderer.paint(gc, textPosX, textPosY);
	}

}
 
Example 17
Source File: MiscHelpers.java    From arma-dialog-creator with MIT License 4 votes vote down vote up
public static void paintFlippedImage(@NotNull GraphicsContext gc, @NotNull Image img, int x, int y, int w, int h) {
	gc.save();
	gc.scale(-1, 1);
	gc.drawImage(img, -x - w, y, w, h);
	gc.restore();
}
 
Example 18
Source File: YOLO2_TF_Client.java    From SKIL_Examples with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Stage stage) throws Exception {

    if (args.input_camera >= 0) {
        System.out.println("Opening camara " + args.input_camera);
        frameGrabber = new OpenCVFrameGrabber(args.input_camera);
        frameGrabber.start();
    }

    labels = new COCOLabels();
    colors = new HashMap<>();
    for (int i = 0; i < nClasses; i++) {
        colors.put( labels.getLabel( i ), Color.web( COLORS[i] ) );
    }

    // make model server network calls for { auth, inference }
    skilClientGetImageInference( );

    Canvas canvas = new Canvas(imageWidth, imageHeight);
    GraphicsContext ctx = canvas.getGraphicsContext2D();

    ctx.drawImage(SwingFXUtils.toFXImage(bufImgConverter.convert(matConverter.convert(imgMat)), null), 0, 0);
    stage.setScene(new Scene(new StackPane(canvas), this.imageWidth, this.imageHeight));
    renderJavaFXStyle( ctx );
    stage.setTitle("YOLO2");
    stage.show();

    if (frameGrabber != null) {
        new Thread(() -> {
            try {
                while (stage.isShowing()) {
                    skilClientGetImageInference( );
                    ctx.drawImage(SwingFXUtils.toFXImage(bufImgConverter.convert(matConverter.convert(imgMat)), null), 0, 0);
                    renderJavaFXStyle( ctx );
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
 
Example 19
Source File: Sprite.java    From Introduction-to-JavaFX-for-Game-Development with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void render(GraphicsContext gc)
{
    gc.drawImage( image, positionX, positionY );
}
 
Example 20
Source File: NinePatch.java    From oim-fx with MIT License 2 votes vote down vote up
/**
 *
 * @param gc
 * @param x
 * @param y
 * @param scaledWidth
 * @param scaledHeight
 */
public void draw(GraphicsContext gc, int x, int y, int scaledWidth, int scaledHeight) {
    gc.drawImage(generate(scaledWidth, scaledHeight), x, y);
}