是否可以在Codename One中保存生成的图像?

时间:2016-06-07 20:39:56

标签: image drawing codenameone stacked

我的问题与this previous question有关。我想要实现的是堆叠图像(它们具有透明度),在顶部写一个字符串,并以全分辨率保存照片蒙太奇/光照片。

    @Override
protected void beforeMain(Form f) {


    Image photoBase = fetchResourceFile().getImage("Voiture_4_3.jpg");
    Image watermark = fetchResourceFile().getImage("Watermark.png");


    f.setLayout(new LayeredLayout());
    final Label drawing = new Label();
    f.addComponent(drawing);


    // Image mutable dans laquelle on va dessiner (fond blanc)
    Image mutableImage = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
    drawing.getUnselectedStyle().setBgImage(mutableImage);
    drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);

    // Paint all the stuff
    paints(mutableImage.getGraphics(), photoBase, watermark, photoBase.getWidth(), photoBase.getHeight());

    // Save the collage
    Image screenshot = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
    f.revalidate();
    f.setVisible(true);
    drawing.paintComponent(screenshot.getGraphics(), true);

    String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
    try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
        ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
    } catch(IOException err) {
        err.printStackTrace();
    }

}

public void paints(Graphics g, Image background, Image watermark, int width, int height) {

    g.drawImage(background, 0, 0);
    g.drawImage(watermark, 0, 0);
    g.setColor(0xFF0000);

    // Upper left corner
    g.fillRect(0, 0, 10, 10);

    // Lower right corner
    g.setColor(0x00FF00);
    g.fillRect(width - 10, height - 10, 10, 10);

    g.setColor(0xFF0000);
    Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
    g.setFont(f);
    // Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
    g.drawString("HelloWorld", 
            (int) (848 ),
            (int) (610)
            );

}

这是我保存的截图,如果我使用Iphone6皮肤Screenshot I get(有效载荷图像小于原始图像并居中)。如果我使用Xoom皮肤,这就是我得到的Screenshot I get with Xoom(有效载荷图像仍然小于原始图像,但它已向左移动)。

总而言之:为什么Xoom皮肤保存的屏幕截图与Iphone皮肤屏幕截图不同?无论如何直接保存我在paint方法中绘制的图形,以便保存的图像具有原始尺寸?

非常感谢能帮助我的人: - )!

干杯,

1 个答案:

答案 0 :(得分:1)

您可以使用ImageIO类在Codename中保存图像。请注意,您可以使用paintComponent(Graphics)方法将容器层次结构绘制为可变图像。

您可以在可变或通过布局绘制图像的两种方法。我个人总是喜欢布局,因为我喜欢抽象,但我不会说可变图像方法是对还是错。

请注意,如果你更改/重绘很多,那么可变图像会更慢(这对于常规代码或模拟器来说不会引人注意),因为它们被迫使用软件渲染器并且无法完全使用GPU

在上一个问题中,您似乎将图像放置在" FIT"风格自然地比包含容器小,然后手动将图像绘制在它上面......这是有问题的。

一种解决方案是手动绘制所有内容,但是您需要执行" fit"画自己的方面。如果使用布局,则应根据布局(包括绘图/文本)定位所有内容。