What is the best way to read pixels of a JavaFX Canvas?

后端 未结 2 1730
后悔当初
后悔当初 2020-12-03 20:11

I want to get the color for specific coordinates inside a Canvas. I already tried getting a snapshot using this code:

WritableImage snap = gc.ge         


        
相关标签:
2条回答
  • 2020-12-03 20:25
    public class Pixel
    {
        private static final SnapshotParameters SP = new SnapshotParameters();
        private static final WritableImage WI = new WritableImage(1, 1);
        private static final PixelReader PR = WI.getPixelReader();
    
        private Pixel()
        {
        }
    
        public static int getArgb(Node n, double x, double y)
        {
            synchronized (WI)
            {
                Rectangle2D r = new Rectangle2D(x, y, 1, 1);
                SP.setViewport(r);
                n.snapshot(SP, WI);
               return PR.getArgb(0, 0);
            }
        }
    
        public static Color getColor(Node n, double x, double y)
        {
            synchronized (WI)
            {
                Rectangle2D r = new Rectangle2D(x, y, 1, 1);
                SP.setViewport(r);
                n.snapshot(SP, WI);
                return PR.getColor(0, 0);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-03 20:38

    A Canvas buffers the drawing instructions prescribed by invoking the methods of a GraphicsContext. There are no pixels to read until the Canvas is rendered in a later pulse, and the internal format of the instruction buffer is not exposed in the API.

    As an alternative, consider drawing into a BufferedImage, illustrated here, which allows access to the image's pixels directly and via its WritableRaster. Adding the following line to this complete example outputs the expected value for opaque red in ARGB order: ffff0000.

    System.out.println(Integer.toHexString(bi.getRGB(50, 550)));
    

    image

    0 讨论(0)
提交回复
热议问题