Convert Shape object to Image object in Java

烈酒焚心 提交于 2019-12-10 21:34:36

问题


How do I convert a Shape object like Rectangle2D.Double to an Image object?

This way I can use a Shape object for a mousecursor replacement.


回答1:


Do draw(shape) in a BufferedImage, as shown here.




回答2:


You'll have to create an image object which contains the right pixels at the right locations.

One way would be something like this:

public Image makeImage(Shape s) {
    Rectangle r = s.getBounds();
    Image image = new BufferedImage(r.width, r.height, BufferedImage.TYPE_BYTE_BINARY);
    Graphics2D gr = image.createGraphics();
    // move the shape in the region of the image
    gr.translate(-r.x, -r.y);
    gr.draw(s);
    gr.dispose();
    return image;
}

You may want to use another color model, though, to have your shape show up with transparent background, instead of black-on-white or otherwise around.



来源:https://stackoverflow.com/questions/5449633/convert-shape-object-to-image-object-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!