Delphi绘制Alpha图像的函数

最近在整理代码的时候发现了这个函数,但是原作者是谁我已经不知道了,修正了里面的一个bug,然后把alpha修改为0-255个级别!(原来为10)

 

 1 procedure DrawAlpha(bmpBack, bmpFore : TBitmap; TransColor : TColor; OffX, OffY : Integer; Alpha : Integer);
 2 
 3 type
 4   TRGBArray = array[0..32767of TRGBTriple;
 5   PRGBArray = ^TRGBArray;
 6 
 7 var
 8   X, Y     : Integer;
 9   rowFore,
10   rowBack  : PRGBArray;
11 
12 begin
13   // check bitmaps
14   if not Assigned(bmpBack) or
15      not Assigned(bmpFore) then
16    Exit;
17 
18   // check color depth
19   if (bmpFore.PixelFormat <> pf24bit) or
20      (bmpBack.PixelFormat <> pf24bit) then
21    Exit;
22 
23 // check dimensions
24 //  if (bmpFore.Height + OffY > bmpBack.Height) or
25 //     (bmpFore.Width + OffX > bmpBack.Width) then
26 //    Exit;
27 
28   // check alpha value
29   if (Alpha > 255or
30      (Alpha < 0then
31     Alpha := 255;
32 
33   for y := 0 to bmpFore.Height - 1 do
34   begin
35     // scan bitmap rows
36     if (y > bmpBack.Width) then
37           Continue;
38     rowBack := bmpBack.ScanLine[y + OffY];
39     rowFore := bmpFore.ScanLine[y];
40     for x := 0 to bmpFore.Width - 1 do
41     begin
42     if (x+offx>bmpBack.Width) then
43           Continue;
44     // if not transparent color
45     if not ((rowFore[x].rgbtRed   = GetRValue(TransColor)) and
46             (rowFore[x].rgbtGreen = GetGValue(TransColor)) and
47             (rowFore[x].rgbtBlue  = GetBValue(TransColor))) then
48     // calculate new pixel value
49     begin
50       rowBack[x + OffX].rgbtRed   := ((rowBack[x + OffX].rgbtRed * (255 - Alpha))   + (rowFore[x].rgbtRed * abs(Alpha-255)))div 255;
51       rowBack[x + OffX].rgbtGreen := ((rowBack[x + OffX].rgbtGreen) * (255 - Alpha) + (rowFore[x].rgbtGreen * Abs(Alpha-255)))div 255;
52       rowBack[x + OffX].rgbtBlue  := ((rowBack[x + OffX].rgbtBlue) * (255 - Alpha)  + (rowFore[x].rgbtBlue * Abs(Alpha-255)))div 255;
53     end;
54   end;
55   end;
56 end;

 

下面的是使用的例子

 

 1 procedure TForm1.Button2Click(Sender: TObject);
 2 begin
 3   // set color depth to 16.7mio colors (24 bit)
 4   // because the loaded bitmaps are 8 bit
 5   img1.Picture.Bitmap.PixelFormat := pf24bit;
 6   img2.Picture.Bitmap.PixelFormat := pf24bit;
 7 
 8   DrawAlpha(img1.Picture.Bitmap, img2.Picture.Bitmap, clFuchsia, 10105);
 9 
10   // update image1 (result)
11   img1.Invalidate;
12 end;

 

 

posted on 2008-09-16 12:37  流浪猫  阅读(1055)  评论(0编辑  收藏  举报

导航