Question

Draw Canvas Rectangle with transparency in Tpicture

Asked by: arreegua

Hi Experts,

I have a big picture in a Tpicture object, it is a map from a game, and i need to show the dangerous zones painting a red rectangle over it, with transparency,  the info in map must be visible.

I dont have a clue how to do it, alpha? rgb manipulation ? really don´t know, if u can provide a code sample , will be much apreciate.

regards

Wilson

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-10 at 06:55:14ID24801559
Topics

Graphics and Delphi Programming

,

Delphi Programming

Participating Experts
5
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Restrict drawing on a canvas into a rectangle?
    I need to specify a rectangle on a canvas where drawing is enabled, and outside it is forbidden. For example, in Rect(25, 25, 200, 200) drawing is enabled, and anything drawn outside it is not displayed. Please note, that the canvas in question is the canvas of a printer. H...
  2. canvas-drawing on top of a video
    Hi ! When "windows" repaints the window (the delphi-form) in which a step of my video is displayed my program automaticaly updates the according step of the video, too. Then it does some canvas-drawing on top of the video, again. But then, the canvas-drawing only wo...
  3. Drawing a rectangle on screen!
    Hi! I want draw a rectagnle on screen! I am writing a screen capture program and I need this functionality for my program! A way that I think over it is capturing entire screen. and then user can draw rectangle on that! But I want to know is there any way to draw a rectagn...
  4. Drawing squares, circles, and painted rectangles in Borl…
    Hi everybody, I'm new in this community and in the C++ also... I know that this question is too easy to answer but I realy would like this help. In C++ Builder I have a form and a ScrollBox. How can I draw a square, a circle, a painted rectangle, a line and write a single ...
  5. Drawing squares, circles, and painted rectangles in Borl…
    Hi everybody, I'm new in this community and in the C++ also... I know that this question is too easy to answer but I realy would like this help. In C++ Builder I have a form and a ScrollBox. How can I draw a square, a circle, a painted rectangle, a line and write a single ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ThievingSixPosted on 2009-10-10 at 19:25:21ID: 25544676

Not sure if pre-Delphi 2009 has the TBitmap.DrawTransperant but if it does then this works fine:

function MakeRectangle(W,H: Integer; BorderColor: TColor; FillColor: TColor): TBitmap;
begin
  Result := TBitmap.Create;
  Result.Width := W;
  Result.Height := H;
  Result.Canvas.Pen.Width := 3;
  Result.Canvas.Pen.Color := BorderColor;
  Result.Canvas.Rectangle(0,0,W,H);
  Result.Canvas.Brush.Color := FillColor;
  Result.Canvas.FillRect(Rect(3,3,W - 3,H - 3));
end;
 
procedure TForm22.Button1Click(Sender: TObject);
var
  MyRectangle : TBitmap;
begin
  MyRectangle := MakeRectangle(200,200,clMaroon,clRed);
  Image1.Canvas.Draw(50,50,MyRectangle,150);
end;
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

 

by: LukA_YJKPosted on 2009-10-10 at 20:55:21ID: 25544810

You might want to use a simpler approach. Paint rectangles with OR or some other combination. Something like below. You can experiment with CopyMode to get the best result. Good luck

procedure PutDangerRect(x, y: integer; Picture: TPicture);
var cm: TCopyMode;
    rt: TRect;
    bm: TBitmap;
begin
  with Picture.Bitmap.Canvas do begin
    cm := CopyMode;
    CopyMode := cmSrcPaint; // Combines the image on the canvas and the source bitmap by using the Boolean OR operator.
    rt := Rect(x-10, y-10, x+10, y+10);
    bm := TBitmap.Create;
    with bm, Canvas do begin
      Width := 20;
      Height := 20;
      Brush.Color := clRed;
      FillRect(ClipRect);
    end;
    CopyRect(rt, bm.Canvas, bm.Canvas.ClipRect);
    CopyMode := cm;
    bm.Free;
  end;
end;
 
// Usage test
 
procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  PutDangerRect(x, y, (Sender as TImage).Picture);
end;
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

Select allOpen in new window

 

by: EddieShipmanPosted on 2009-10-11 at 09:44:32ID: 25546469

All you have to do is set the Brush.Style to bsClear then your rect will have a transparency

 

by: ThievingSixPosted on 2009-10-11 at 17:44:42ID: 25548067

EddieShipman: Wouldn't that give complete transparency? I think the user wants partial.

 

by: MvanderKooijPosted on 2009-10-12 at 02:22:20ID: 25549578

I think you can best create 2 bitmaps and merge them before showing to the user.

To merge them you could use the AlphaBlend funtion of microsoft, but i've seen some differences between XP and Vista, so i have assamblied my own version together. See code.

It can handle tranparancy per pixel and a global value.

If you put the map in the destination bitmap, and the overlay in the second, then you can call the method with a 128 transparancy to merge them together. Or set the transparancy per pixel in the source bitmap

Type
  // Assumes a 32 bit TBitmap pixel type  i.e. TBitmap.PixelFormat := pf32bit;
  RGB_Pixel = Packed Record  // Variant record allow two separate fields to occupy the same memory space
                Case LongWord of
                  0 : ( Blue, Green, Red, Alpha : Byte );  // This is Windows specific as an RGB pixel has its colour channels ordered in a specific way i.e. ABGR rather than the usual RGBA
                  1 : ( All_Channels : LongWord );         // The above colour components can be accessed as a single unsigned 32-bit integer when All_Channels field is accessed.
                End;                                       // This is useful for performing AND, XOR, OR and other bitwise manipulations on an entire pixel
 
  // A pointer to the above pixel record type
  RGB_Pixel_Pointer = ^RGB_Pixel;
 
  {
  An array of the above RGB pixel type which makes it easy to access a region
  of memory containing a series of RGB pixels. This is used by many graphics
  filters or rendering routines.
 
  Packed Array forces the individual fields to be aligned close together in memory.
  Some operating systems or compilers, if not declared as packed, would align fields on 16-bit or 32-bit boundaries
  depending upon the size of an individual field.  The Delphi specific identifier "Packed"
  gives us the ability to force record fields to be close together with no free byte space in between.
 
  An array of this size allows us to access a scanline in a bitmap that
  has a maximum width of 32767 pixels, Increase this if you need to
  access larger bitmaps.
  }
  Array_of_RGB_Pixels = Packed Array[ 0..32767 ] of RGB_Pixel;
 
  {
  A pointer to an Array of RGB pixels which makes it easy to access a region
  of memory containing a series of RGB pixels. This is used by many graphics
  filters or rendering routines that need to facilitate pointer arithmetic
  or memory address manipulation on a whole series of RGB pixels.
  }
  Pointer_to_Array_of_RGB_Pixels = ^Array_of_RGB_Pixels;
 
procedure AlphaBlendBitmap(dest: TBitmap; src: TBitmap; trans: byte);
var
  LineOfDest: Pointer_to_Array_of_RGB_Pixels;
  LineOfSrc: Pointer_to_Array_of_RGB_Pixels;
  iLastX, iLastY: integer;
  x,y: integer;
  PixelDest: RGB_Pixel;
  PixelSrc: RGB_Pixel;
  iAlphaPart: integer;
begin
  iLastX := min(dest.Width -1, src.Width -1);
  iLastY := min(dest.Height -1, src.Height -1);
  dest.PixelFormat := pf32bit;
  src.PixelFormat := pf32bit;
 
  for y := 0 to iLastY do begin
    LineOfDest := dest.ScanLine[y];
    LineOfSrc := src.ScanLine[y];
    for x := 0 to iLastX do begin
      PixelDest := LineOfDest[ x ];
      PixelSrc := LineOfSrc[ x ];
 
      iAlphaPart := (PixelSrc.Alpha * trans) SHR 8;
 
      LineOfDest[ x ].Blue  := ( ( iAlphaPart * ( PixelSrc.Blue  ) ) + ((255 - iAlphaPart) * PixelDest.Blue))  SHR 8;
      LineOfDest[ x ].Green := ( ( iAlphaPart * ( PixelSrc.Green ) ) + ((255 - iAlphaPart) * PixelDest.Green)) SHR 8;
      LineOfDest[ x ].Red   := ( ( iAlphaPart * ( PixelSrc.Red   ) ) + ((255 - iAlphaPart) * PixelDest.Red))   SHR 8;
    end;
  end;
end;

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:

Select allOpen in new window

 

by: arreeguaPosted on 2009-10-13 at 05:53:18ID: 25559307

Hi Experts,

Sorry about the delay, last monday was hollyday here in brazil. I ll test the suggestions, and be rigth back.

Thankyou so much for help.

 

by: EddieShipmanPosted on 2009-10-13 at 08:57:47ID: 25561309

TheivingSix,
If you draw a rectangle OVER a bitmap with bsClear, the bitmap below will show through.

 

by: HypoPosted on 2009-10-13 at 09:14:12ID: 25561472

I like these kinds of problems, so here's my two cents...
For simple functionality i would probably only change the CopyMode of the brush, but if I had to have real alpha blending I would create something like the following functionality.
 
The AlphaBlendRect uses the AlphaBlend function of the Windows API to blend a small bitmap (1x1 pixels) to the target Canvas... easy to understand and to use.

If you promptly have to paint it on to a picture object, then You can use the AlphaBlendRectToGraphic function and pass the Picture.Graphics object as a parameter, (since afaik, that's the only object you'll know always exist on the picture object).

See the examples below...

/Hypo

Procedure AlphaBlendRect(ACanvas : TCanvas; ARect : TRect; AColor : TColor; AOpacity : Byte = 255);
var aBitmap : TBitmap;
    aBlendFunc : TBlendFunction;
begin
  aBitmap := TBitmap.Create;
  try
    aBitmap.PixelFormat := pf32Bit;
    aBitmap.Width := 1;
    aBitmap.Height := 1;
    aBitmap.Canvas.Pixels[0, 0] := AColor;
 
    aBlendFunc.BlendOp := AC_SRC_OVER;
    aBlendFunc.BlendFlags := 0;
    aBlendFunc.SourceConstantAlpha := AOpacity;
    aBlendFunc.AlphaFormat := AC_SRC_ALPHA;
 
    Windows.AlphaBlend(ACanvas.Handle,
                       ARect.Left,
                       ARect.Top,
                       ARect.Right-ARect.Left,
                       ARect.Bottom-ARect.Top,
                       aBitmap.Canvas.Handle,
                       0, 0, 1, 1,
                       aBlendFunc);
  finally
    aBitmap.Free;
  end;
end;
 
Procedure AlphaBlendRectToGraphic(AGraphic : TGraphic; ARect : TRect; AColor : TColor; AOpacity : Byte = 255);
var aTmpBitmap : TBitmap;
begin
  aTmpBitmap := TBitmap.Create;
  try
    aTmpBitmap.Assign(AGraphic);
    AlphaBlendRect(aTmpBitmap.Canvas, ARect, AColor, AOpacity);
    AGraphic.Assign(aTmpBitmap);
  finally
    aTmpBitmap.Free;
  end;
end;
 
---
 
// Trackbar range from 0 to 255...
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
  Repaint;
  AlphaBlendRect(Canvas, Image1.BoundsRect, clRed, TrackBar1.Position);
end;
 
procedure TForm1.Button2Click(Sender: TObject);
begin
  AlphaBlendRectToGraphic(Image1.Picture.Graphic, Rect(0, 0, Image1.Picture.Width div 2, Image1.Picture.Height div 2), clRed, 255);
  Image1.Repaint;
end;
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:

Select allOpen in new window

 

by: ThievingSixPosted on 2009-10-13 at 09:34:12ID: 25561649

FYI:

 Image1.Canvas.Draw(W,H,Graphic,Opacity);

Which utilizes

 TBitmap.DrawTransperant;

Is the AlphaBlend WinAPI function.

 

by: arreeguaPosted on 2009-10-13 at 11:28:18ID: 31639619

Thankyou so much to all you that helped me. Like always the hard part is wich answer accepet.

This time, i choose the first complete answer that worked to me, so thankyou thievingsix.

Thankyou all

Wilson

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...