Search code examples
codenameonetransparency

Codename One - transparent foreground and fonts


I have not yet found any option to provide transparency to the foreground color of a component, or to the font for that matter.

What I want to do is:

    Label halfTransparentLabel = new Label("Half Transparent text");
    Style s = halfTransparentLabel.getAllStyles();
    s.setBgColor(0);
    s.setBgTransparency(255);
    s.setFgColor(0xffffff);
    s.setFgTransparency(128); // this method does not exist

I know drawing translucent stuff is heavy on the performance, but I want to do it on particular pieces only. would greatly improve the visual appeal and design, having this option.

Can this be worked around?


Solution

  • UPDATED ANSWER

    Thanks to the Shai's comment, I update my answer. The workaround I suggested is not necessary. The same result of the posted screenshot can be obtained with https://www.codenameone.com/javadoc/com/codename1/ui/plaf/Style.html#setOpacity-int- or with the opacity property in the CSS, for example:

    BigLabel {
        font-size: 6mm;
        font-family: "native:MainRegular";
        color: red;
        background-color: transparent;
        opacity: 0.5;
    }
    

    OLD ANSWER - Yes, it's possible to workaround this problem using the .toImage() method, as in this screenshot:

    Codename One Semi-transparent text

    I'm not sure if this workaround is the best, however it works. The code of this example:

    Form hi = new Form("Semitransparent Example", BoxLayout.y());
    hi.getToolbar().setUIID("Transparent");
    hi.setUIID("FormBackground");
    
    Container cnt = FlowLayout.encloseIn(new Label("Half Transparent Text", "BigLabel"));
    // .setSize() and .revalidate(), in this case, are necessary to use the .image() method
    cnt.setSize(new Dimension(hi.getContentPane().getWidth(), CN.convertToPixels(8, false)));
    cnt.revalidate();
    hi.add(cnt.toImage().modifyAlpha((byte) 125));
    
    hi.show();
    

    and the CSS:

    #Constants {
        includeNativeBool: true; 
    }
    
    Transparent {
        background-color: transparent;
    }
    
    FormBackground {
        background-image: url("background.jpg");
    }
    
    BigLabel {
        font-size: 6mm;
        font-family: "native:MainRegular";
        color: red;
        background-color: transparent;
    }