Cralias
Cralias

Reputation: 105

Modify per-pixel alpha data for TPngImage

Can I directly modify per-pixel alpha data for TPngImage between loading it from somewhere and drawing it somewhere? If so, how? Thanks.

Upvotes: 6

Views: 1561

Answers (2)

rsachetto
rsachetto

Reputation: 175

You could use something like this:

for Y := 0 to Image.Height - 1 do begin
  Line := Image.AlphaScanline[Y];
  for X := 0 to Image.Width - 1 do begin        
      Line[X] := ALPHA        
  end;
end;

Upvotes: 3

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

Yes, I think that is easy.

For example, this code will set the opacity to zero (that is, the transparency to 100 %) on every pixel in the upper half of the image:

var
  png: TPNGImage;
  sl: PByteArray;

...

for y := 0 to png.Height div 2 do
begin
  sl := png.AlphaScanline[y];
  FillChar(sl^, png.Width, 0);
end;

This will make a linear gradient alpha channel, from full transparency (alpha = 0) to full opacity (alpha = 255) from left to right:

for y := 0 to png.Height do
begin
  sl := png.AlphaScanline[y];
  for x := 0 to png.Width - 1 do
    sl^[x] := byte(round(255*x/png.Width));
end;

Basically, what I am trying to say, is that

(png.AlphaScanline[y]^)[x]

is the alpha value (the opacity), as a byte, of the pixel at row y and col x.

Upvotes: 9

Related Questions