1
votes

I am drawing lines by using win32 gdi native apis. Now, I want to draw the line as transparent. I have set the alpha channel property in the color. However, setting the alpha channel in color is not drawing the line as transparent. I read about Alpha Blend Api but could not figure out the solution.

var hdc = g.GdiDeviceContext;
var srcHdc = CreateCompatibleDC(hdc);

var clipRegion = CreateRectRgn(x, y, x + width, y + height);

SelectClipRgn(hdc, clipRegion);

var pen = CreatePen(PenStyle.Solid, LineWidth, (uint)ColorTranslator.ToWin32(colour));



if (pen != IntPtr.Zero)
{
     var oldPen = SelectObject(hdc, pen);
     Polyline(hdc, points, points.Length);
     SelectObject(hdc, oldPen);
     DeleteObject(pen);
}

SelectClipRgn(hdc, IntPtr.Zero);
AlphaBlend(hdc, x, y, width, height, srcHdc, x, y, width, height, new BlendFunction(0x00, 0, 0x7f, 0x00));
DeleteObject(clipRegion);

I am trying to draw the line as transparent.

1
"it is not working" is not a problem statement. Explain, what you expect to happen, as well as the observed behavior. It's also highly recommended that you use symbolic constants. As written, we have no idea, what properties your BLENDFUNCTION is supposed to have. - IInspectable
GDI harks from the olden days, it is a 24bpp api. Bump up to GDI+, gdiplus.h header file. - Hans Passant
@lInspectable I have modified the question. docs.microsoft.com/en-us/windows/desktop/api/wingdi/… and docs.microsoft.com/en-us/windows/desktop/api/wingdi/… are native win32 api and structures. - Richa Garg

1 Answers

1
votes
var srcHdc = CreateCompatibleDC(hdc);

This creates a memory device context. This is the right first step. But the memory dc is not ready yet. It requires a memory bitmap as well.

SelectObject(hdc, pen);
Polyline(hdc, points, points.Length);

This will draw on windows device context. But we want to draw on memory device context, and then draw the memory on to HDC using AlphaBlend

See example below:

int w = 100;
int h = 100;

//create memory device context
var memdc = CreateCompatibleDC(hdc); 

//create bitmap
var hbitmap = CreateCompatibleBitmap(hdc, w, h);

//select bitmap in to memory device context
var holdbmp = SelectObject(memdc, hbitmap);

//begine drawing:
var hpen = CreatePen(0, 4, 255);
var holdpen = SelectObject(memdc, hpen);
Rectangle(memdc, 10, 10, 90, 90);

//draw memory device (memdc) context on to windows device context (hdc)
AlphaBlend(hdc, 0, 0, w, h, memdc, 0, 0, w, h, new BLENDFUNCTION(0, 0, 128, 0));

//clean up:
SelectObject(memdc, holdbmp);
SelectObject(memdc, holdpen);
DeleteObject(hbitmap);
DeleteObject(hpen);
DeleteDC(memdc);