CreateFromBitmapAndMask (Delphi)

Contents

Description

This example shows how to use the CreateFromBitmapAndMask constructor. The example allows you to load two images (an initial bitmap and a mask), resizes them to the same size, and then creates a new image by applying the mask over the initial image.

To build and test this example, create a Multi-Device Application - Delphi, then add the next objects to the form:

Add the following code to the OnClick event handlers of the button to create and display the result. The nested CenterCopy and CreateSameSizeBitmaps procedures are used to resize the initial bitmap and the mask to the same size. One uses the Min function, which is part of the Math unit.

procedureTForm1.Button3Click(Sender:TObject);// The source bitmap and the mask will have the same sizeprocedureCenterCopy(Source,Target:TBitmap);varX,Y:integer;TopLeft:TPoint;Rect:TRect;beginX:=Source.Widthdiv2;Y:=Source.Heightdiv2;//Define the top left corner of the rectangle to be copiedTopLeft:=Point(X-Target.Widthdiv2,Y-Target.Heightdiv2);//Define the rectangle to be copiedRect:=TRect.Create(TopLeft,Target.Width,Target.Height);Target.CopyFromBitmap(Source,Rect,0,0);end;procedureCreateSameSizeBitmaps(Source1,Source2:TBitmap;varTarget1,Target2:TBitmap);varminX,minY:Integer;begin// Resizes the initial bitmap and the mask to the same sizes// Finds the size of the result bitmapminX:=Min(Source1.Width,Source2.Width);minY:=Min(Source1.Height,Source2.Height);Target1:=TBitmap.Create(minX,minY);Target2:=TBitmap.Create(minX,minY);// Resizes to the initial bitmapCenterCopy(Source1,Target1);// Resizes to the maskCenterCopy(Source2,Target2);end;varBitmap1,Bitmap2,Bitmap3:TBitmap;begin// Resizes the source and the maskCreateSameSizeBitmaps(Image1.Bitmap,Image2.Bitmap,Bitmap1,Bitmap2);try// Creates the final bitmap by applying the mask over the sourceBitmap3:=TBitmap.CreateFromBitmapAndMask(Bitmap1,Bitmap2);try// Displays the resultImage3.Bitmap:=Bitmap3;// Image3.Bitmap.UpdateHandles;finally// Frees the result bitmapBitmap3.Free;end;// Displays the resized images (source and mask)Image4.Bitmap:=Bitmap1;Image5.Bitmap:=Bitmap2;finally// Frees the resized source and mask bitmapsBitmap2.Free;Bitmap1.Free;end;end;