Any way to make GtkProgressBar have a transparent background? - coding-style

So far I've not been able to find any way to make the background of a GtkProgressBar transparent. I've tried setting a transparent image as the background, but the alpha channel is ignored. Can this be done?

Gtk doesn't have mechanisms to handle transparency.
It would create significant performance penalty. Even changes in covered parts of the widgets would have to generate expose events.
I guess there should be a method to composite widgets in your own way. But I think it'd be a lot of work to implement in C/Gtk. In C++/gtkmm it wouldn't be that hard to implement custom widget which does all the rendering itself.

You can try it using gtkrc file.
Try to do something like this.
`style "tc-theme-ProgressBar"
{
xthickness = 1
ythickness = 1
engine "pixmap"
{
image
{
function = BOX
orientation = HORIZONTAL
file = "./buttons/TransparentImage.png"
border = { 0, 0, 0, 0} # = {Left, Right, Top, Bottom}
stretch = TRUE #This stretches the image
}
}
}
class "GtkProgressBar" style "tc-theme-ProgressBar"
'

Related

Is it possible to save a generated image in Codename One?

My question is related to this previous question. What I want to achieve is to stack images (they have transparency), write a string on top, and save the photomontage / photocollage with full resolution.
#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)
);
}
This is the saved screenshot I get if I use the Iphone6 skin (the payload image is smaller than the original one and is centered). If I use the Xoom skin this is what I get (the payload image is still smaller than the original image but it has moved to the left).
So to sum it all up : why is the saved screenshot with Xoom skin different from the one I get with Iphone skin ? Is there anyway to directly save the graphics on which I paint in the paints method so that the saved image would have the original dimensions ?
Thanks a lot to anyone that could help me :-)!
Cheers,
You can save an image in Codename one using the ImageIO class. Notice that you can draw a container hierarchy into a mutable image using the paintComponent(Graphics) method.
You can do both approaches with draw image on mutable or via layouts. Personally I always prefer layouts as I like the abstraction but I wouldn't say the mutable image approach is right/wrong.
Notice that if you change/repaint a lot then mutable images are slower (this will not be noticeable for regular code or on the simulator) as they are forced to use the software renderer and can't use the GPU fully.
In the previous question it seems you placed the image with a "FIT" style which naturally drew it smaller than the containing container and then drew the image on top of it manually... This is problematic.
One solution is to draw everything manually but then you will need to do the "fit" aspect of drawing yourself. If you use layouts you should position everything based on the layouts including your drawing/text.

Win32 LayeredWindow gives bad visual effect

I'm developing a UI system that has all those smart features like panel tearing off and docking, etc. Right now my task is to create an overlay on the screen that shows the position where the teared off or dockable panel would land. Pretty much same thing that visual studio has got.
For that I'm using a custom layered window class that would show up when it is needed. After that I've started digging to achieve the needed effect.
I was working with standart GDI functions before and basicly they are ok. But this time I followed the documentation advice to use UpdateLayeredWindow for my tasks and to load 32bit image from bitmap instead of drawing it with GDI functions.
So here I have a 128x128pixel wide bmp with 222 in alpha channel and 255 0 0 in RGB
Here are methods which I use for initialization and drawing.
void Init(HDC in_hdc,HWND in_hwnd)
{
bf = { 0, 0, 200, AC_SRC_ALPHA };
hwnd = in_hwnd;
hdc_mem = CreateCompatibleDC(in_hdc);
hBitmap_mem = CreateCompatibleBitmap(in_hdc, canvas_size.cx, canvas_size.cy);
hBitmap_mem_default = (HBITMAP)SelectObject(hdc_mem, hBitmap_mem);
hdc_bitmap = CreateCompatibleDC(in_hdc);
}
void DrawArea(RECT& in_rect)
{
hBitmap_area_default = (HBITMAP)SelectObject(hdc_bitmap, hBitmap_area);
AlphaBlend(hdc_mem, in_rect.left, in_rect.top, in_rect.right, in_rect.bottom, hdc_bitmap, 0, 0, 2, 2, bf);
hBitmap_area = (HBITMAP)SelectObject(hdc_bitmap, hBitmap_area_default);
}
void Update()
{
POINT p = { 0, 0 };
HDC hdc_screen = GetDC(0);
UpdateLayeredWindow(hwnd, hdc_screen, &p, &canvas_size, hdc_mem, &p, 0, &bf, ULW_ALPHA);
}
The window style has this extras
WS_EX_LAYERED|WS_EX_TRANSPARENT|WS_EX_TOPMOST
And here is what I get.
So as you can see the blending that takes place DOES take into account per-pixel alpha, but it does a bad blending job.
Any ideas how to tune it?
I suspect the problem is in the source bitmap. This is the kind of effect you get when the RGB values aren't premultiplied with the alpha. But ignore that because there is a far simpler way of doing this.
Create a layered window with a solid background colour by setting hbrBackground in the WNDCLASSEX structure.
Make the window partially transparent by calling SetLayeredWindowAttributes.
Position the window where you want it.
That's it.
This answer has code that illustrates the technique for a slightly different purpose.

Parallax Scrolling SpriteKit

I have found a tutorial on parallax scrolling in spritekit using objective-C though I have been trying to port it to swift without much success, very little in fact.
Parallax Scrolling
Does anyone have any other tutorials or methods of doing parallax scrolling in swift.
This is a SUPER simple way of starting a parallax background. WITH SKACTIONS! I am hoping it helps you understand the basics before moving to a harder but more effective way of coding this.
So I'll start with the code that get a background moving and then you try duplicating the code for the foreground or objects you want to put in your scene.
//declare ground picture. If Your putting this image over the top of another image (use a png file).
var groundImage = SKTexture(imageNamed: "background.jpg")
//make your SKActions that will move the image across the screen. this one goes from right to left.
var moveBackground = SKAction.moveByX(-groundImage.size().width, y: 0, duration: NSTimeInterval(0.01 * groundImage.size().width))
//This resets the image to begin again on the right side.
var resetBackGround = SKAction.moveByX(groundImage.size().width, y: 0, duration: 0.0)
//this moves the image run forever and put the action in the correct sequence.
var moveBackgoundForever = SKAction.repeatActionForever(SKAction.sequence([moveBackground, resetBackGround]))
//then run a for loop to make the images line up end to end.
for var i:CGFloat = 0; i<2 + self.frame.size.width / (groundImage.size().width); ++i {
var sprite = SKSpriteNode(texture: groundImage)
sprite.position = CGPointMake(i * sprite.size.width, sprite.size.height / 2)
sprite.runAction(moveBackgoundForever)
self.addChild(sprite)
}
}
//once this is done repeat for a forground or other items but them run at a different speed.
/*make sure your pictures line up visually end to end. Just duplicating this code will NOT work as you will see but it is a starting point. hint. if your using items like simple obstructions then using actions to spawns a function that creates that obstruction maybe a good way to go too. If there are more then two separate parallax objects then using an array for those objects would help performance. There are many ways to handle this so my point is simple: If you can't port it from ObjectiveC then rethink it in Swift. Good luck!

PySDL2: Renderer or Window Surface for handling colors and text?

My question concerns the sdl2.ext.Renderer mainly, and has to do with a problem I've encountered when trying to render sprites on a sdl2.ext.Window surface.
So right now, for coloring my background on an SDL2 Window, I make the following call:
White = sdl2.ext.Color(255,255,255)
class Background(sdl2.ext.SoftwareSpriteRenderSystem):
def __init__(self,window):
super(Background,self).__init__(window)
sdl2.ext.fill(self.surface,White)
This colors the surface of the Window with a white background. However, I also want to display text on the screen. This is done by creating a TextureSprite using the from_text method of the sdl2.ext.SpriteFactory class as follows:
Renderer = sdl2.ext.Renderer(W) # Creating Renderer
ManagerFont = sdl2.ext.FontManager(font_path = "OpenSans.ttf", size = 14) # Creating Font Manager
Factory = sdl2.ext.SpriteFactory(renderer=Renderer) # Creating Sprite Factory
Text = Factory.from_text("Unisung Softworks",fontmanager=ManagerFont) # Creating TextureSprite from Text
Renderer.copy(Text, dstrect= (0,0,Text.size[0],Text.size[1])) # Resizing the Texture to fit the text dimensions when rendered
The problem occurs when the event loop is run.
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
if event.type == sdl2.SDL_MOUSEBUTTONDOWN:
pass
Renderer.copy(Text, dstrect= (0,0,Text.size[0],Text.size[1]))
Renderer.present() # Problem 1
W.refresh() # Problem 2
return 0
Full Example Paste
When both Renderer.present() and W.refresh() are called, I get a flickering effect from the screen. This seems to be because the Renderer overwrites the White colored Window surface, which then gets colored over again by the Window.refresh() call. This then repeats, resulting in a flickering mess.
I would like to know what I can do to solve this problem? Should I even be using both Window.refresh() and the Renderer at the same time? Is there a way to let one render the other? (Renderer renders background for example). If anyone can help me out, that would be great.
The problem is that you are using Window.refresh() along with a SDL_Renderer and a SoftwareSpriteSystem with SDL_Texture objects.
As outlined in the PySDL2 docs, this is likely to break (since software surface buffers get mixed with hardware-based textures) and you should avoid it. If you want to color the window background, you should use Renderer.clear(White) instead of your Background class and call it before copying the text via Renderer.copy():
Renderer.clear(White)
Renderer.copy(Text, dstrect= (0,0,Text.size[0],Text.size[1]))
Renderer.present()
Do not forget to change the color for your FontManager. By default it uses a white text color, so you should change it to e.g. your Red color:
ManagerFont = sdl2.ext.FontManager(font_path = "OpenSans.ttf", size = 14, color=Red)

How to fade a background-image to transparency?

Here's a related image:
I want to achieve something like what's pictured on the right side of my image. But I also have a parent container that has a background image of its own, instead of a solid color.
Any advice?
EDIT: Forgot to add, cross-browser compatibility is important. (Or atleast Firefox).
I can only think of one pure CSS solution and it is simply insane.
Let's say your image has a width of 100px. You'll have to create a div that's 100px wide and give it 100 children that are each 1px wide, that each have the same background (positioned accordingly) and that each have an opacity from 0 (the first child) to .99 (the last child).
Personally, I think it's crazy and I'd never use this method.
Rory O'Kane came with a nice and clean solution and I also have another idea which involves JavaScript.
Basically, the idea is that you use a canvas element (support), draw your image on it, loop through its pixels and adjust the alpha for each.
demo
(scroll down to see the result)
Relevant HTML:
<div class='parent'>
<canvas id='c' width='575' height='431'></canvas>
</div>
Relevant CSS (setting the background image on the parent)
.parent {
background: url(parent-background.jpg);
}
JavaScript:
window.onload = function() {
var c = document.getElementById('c'),
ctxt = c.getContext('2d'),
img = new Image();
img.onload = function() {
ctxt.drawImage(img, 0, 0);
var imageData = ctxt.getImageData(0, 0, 575, 431);
for(var i = 0, n = imageData.data.length; i < n; i += 4) {
imageData.data[i + 3] = 255*((i/4)%575)/575;
}
ctxt.putImageData(imageData, 0, 0);
};
/* images drawn onto the canvas must be hosted on the same web server
with the same domain as the code executing it */
/* or they can be encoded like in the demo */
img.src = 'image-drawn-on-canvas.jpg';
};
check these out maybe helpful
DEMO 1
DEMO 2
Ignoring possible CSS-only methods, you can make the image a PNG with the transparent gradient built in to the image’s alpha channel. All browsers support PNG transparency, except for IE 6 and below. Here’s what your sample image would look like as a PNG with a transparent gradient (try putting this image against other backgrounds):
If the images are user-submitted so you can’t add the gradient ahead of time, you could create and store a gradient-added version of each image at the time that the user uploads them.
CSS only method:
https://gist.github.com/3750808

Resources