Sign in Join
Wiki copytemporary

Revision 1 of 1, by Trev on 2-9-2020. The page as it is now.

Developing with Graphics/ko

� 페�지는 비트맵과 다른 그래픽들 다루는 튜토리얼� 시작� � 것�다. 나는 프로그래머가 아니지만, �신� 경험� 나눌 수 있는 사람� 누구나 다 초대한다! 다� 섹션� ��를 추가하고 페�지를 �하고 �신� WiKi 문서를 만들기만 하면 �다.

� 페�지�선 �반�� 정보를 줄 것�다.

��브러리

그래픽 ��브러리 - �곳�서는 개발� 사용할 수 있는 주요한 그래픽 ��브러리 들� 볼 수 있� 것�다.

다른 그래픽 문서

2D 그리기

3D 그리기

챠트

LCL� 그래픽 모�� 대한 소개

The LCL provides two kinds of drawing class: Native classes and non-native classes. Native graphics classes are the most traditional way of drawing graphics in the LCL and are also the most important one, while the non-native classes are complementary, but also very important. The native classes are mostly located in the unit Graphics of the LCL and are the well known classes: TBitmap, TCanvas, TFont, TBrush, TPen, TPortableNetworkGraphic, etc.

TCanvas is a class capable of executing drawings. It cannot exist alone and must either be attached to something visible (or at least which may possibly be visible), such as a visual control descending from TControl, or be attached to an off-screen buffer from a TRasterImage descendent (TBitmap is the most commonly used). TFont, TBrush and TPen describe how the drawing of various operations will be executed in the Canvas.

TRasterImage (usually used via its descendant TBitmap) is a memory area reserved for drawing graphics, but it is created for maximum compatibility with the native Canvas and therefore in LCL-Gtk2 in X11 it is located in the X11 server, which makes pixel access via the Pixels property extremely slow. In Windows it is very fast because Windows allows creating a locally allocated image which can receive drawings from a Windows Canvas.

Besides these there are also non-native drawing classes located in the units graphtype (TRawImage), intfgraphics (TLazIntfImage) and lazcanvas (TLazCanvas, this one exists in Lazarus 0.9.31+). TRawImage is the storage and description of a memory area which contains an image. TLazIntfImage is an image which attaches itself to a TRawImage and takes care of converting between TFPColor and the real pixel format of the TRawImage. TLazCanvas is a non-native Canvas which can draw to an image in a TLazIntfImage.

The main difference between the native classes and the non-native ones is that the native ones do not perform exactly the same in all platforms, because the drawing is done by the underlying platform itself. The speed and also the exact final result of the image drawing can have differences. The non-native classes are guaranteed to perform exactly the same drawing in all platforms with a pixel level precision and they all perform reasonably fast in all platforms.

In the widgetset LCL-CustomDrawn the native classes are implemented using the non-native ones.

All of these classes will be better described in the sections below.

TCanvas로 작업하기

디�트 GUI �트 사용하기

다� 샘플코드로 사용� 가능하다:

pascal
SelectObject(Canvas.Handle, GetStockObject(DEFAULT_GUI_FONT));

�� 제한� �스트 그리기

DrawText 루틴� 사용해�, 처��는 DT_CALCRECT와 함께 다��는 없� 사용한다.

pascal
// First calculate the text size then draw it
      TextBox := Rect(0, currentPos.Y, Width, High(Integer));
      DrawText(ACanvas.Handle, PChar(Text), Length(Text),
        TextBox, DT_WORDBREAK or DT_INTERNAL or DT_CALCRECT);
    
      DrawText(ACanvas.Handle, PChar(Text), Length(Text),
        TextBox, DT_WORDBREAK or DT_INTERNAL);

날카로운 �지를 가진 �스트 그리기(안티알리아싱 없�)

몇몇 위젯 다�� 통해 �를 지�한다:

pascal
Canvas.Font.Quality:=fqNonAntialiased

gtk2 같� 몇몇 위젯 셋� �를 지�하지 않고 항� 엘리아스로 그린다. gtk2�서 날카로운 모서리를 가진 �스트를 그리는 간단한 procedure가 있다. 모든 경우를 고려한 것� 아니고 아�디어만 제공한다:

pascal
procedure PaintAliased(Canvas: TCanvas; x,y: integer; const TheText: string);
    var
      w,h: integer;
      IntfImg: TLazIntfImage;
      Img: TBitmap;
      dy: Integer;
      dx: Integer;
      col: TFPColor;
      FontColor: TColor;
      c: TColor;
    begin
      w:=0;
      h:=0;
      Canvas.GetTextSize(TheText,w,h);
      if (w<=0) or (h<=0) then exit;
      Img:=TBitmap.Create;
      IntfImg:=nil;
      try
        // 비트맵� �스트를 그림
        Img.Masked:=true;
        Img.SetSize(w,h);
        Img.Canvas.Brush.Style:=bsSolid;
        Img.Canvas.Brush.Color:=clWhite;
        Img.Canvas.FillRect(0,0,w,h);
        Img.Canvas.Font:=Canvas.Font;
        Img.Canvas.TextOut(0,0,TheText);
        // 메모리 �미지를 얻어온다
        IntfImg:=Img.CreateIntfImage;
        // 회색 픽셀� 치환
        FontColor:=ColorToRGB(Canvas.Font.Color);
        for dy:=0 to h-1 do begin
          for dx:=0 to w-1 do begin
            col:=IntfImg.Colors[dx,dy];
            c:=FPColorToTColor(col);
            if c<>FontColor then
              IntfImg.Colors[dx,dy]:=colTransparent;
          end;
        end;
        // 비트맵 �성
        Img.LoadFromIntfImage(IntfImg);
        // 페�트
        Canvas.Draw(x,y,Img);
      finally
        IntfImg.Free;
        Img.Free;
      end;
    end;

TBitmap과 다른 TGraphics ��으로 작업하기

TBitmap �체는 스�린� 보여주기 전� 비트맵� 저장한다. 비트맵� �성할 때 높�와 넓�를 지정해야만 하며 지정하지 않으면 �기는 0� �고 아무것� 그릴 수 없게 �다. 그리고 �반�으로 모든 다른 TRasterImage � ��들� ��한 능력� 제공한다. 디스��서 입출력하려는 �맷과 �치하는 것� 사용하여야 하며 그렇지 않다면 윈�우즈 비트맵(*bmp)� 경우 TBitmap� 관한 디스� �작� 수행�지 않� 것�다.

(맨 먼저 기억해야 할 것� ��루스는 플랫�� �립���는 것�므로, 윈�우즈 API 함수를 사용하는 어떠한 메�드� 질문� 대�� 아니�는 것�다. 그러므로 ScanLine 같� 메�드는 ��루스�서 지�하지 않는다. ��루스는 장치 �립�� Bitmap과 GDI32.dll� 있는 함수를 사용하고� 하기 때문입니다

당신� TBitmap� 높�와 �� 정�하지 않았다면 그것� 표준�� 것�고 매우 작� 것��는 것� 명심해�)

Loading/Saving an image from/to the disk

To load an image from the disk use TGraphic.LoadFromFile and to save it to another disk file use TGraphic.SaveToFile. Use the appropriate TGraphic descendent which matches the format expected. See Developing_with_Graphics#Image_formats for a list of available image format classes.

pascal
var
      MyBitmap: TBitmap;
    begin
      MyBitmap := TBitmap.Create;
      try
        // Load from disk
        MyBitmap.LoadFromFile(MyEdit.Text);
    
        // Here you can use MyBitmap.Canvas to read/write to/from the image
    
        // Write back to another disk file
        MyBitmap.SaveToFile(MyEdit2.Text);
      finally
        MyBitmap.Free;
      end;
    end;

When using any other format the process is compelely identical, just use the adequate class. For example, for PNG images:

pascal
var
      MyPNG: TPortableNetworkGraphic;
    begin
      MyPNG := TPortableNetworkGraphic.Create;
      try
        // Load from disk
        MyPNG.LoadFromFile(MyEdit.Text);
    
        // Here you can use MyPNG.Canvas to read/write to/from the image
    
        // Write back to another disk file
        MyPNG.SaveToFile(MyEdit2.Text);
      finally
        MyPNG.Free;
      end;
    end;

If you don't know beforehand the format of the image, use TPicture which will determine the format based in the file extension. Note that TPicture does not support all formats supported by Lazarus, as of Lazarus 0.9.31 it supports BMP, PNG, JPEG, Pixmap and PNM while Lazarus also supports ICNS and other formats:

pascal
var
      MyPicture: TPicture;
    begin
      MyPicture := TPicture.Create;
      try
        // Load from disk
        MyPicture.LoadFromFile(MyEdit.Text);
    
        // Here you can use MyPicture.Graphic.Canvas to read/write to/from the image
    
        // Write back to another disk file
        MyPicture.SaveToFile(MyEdit2.Text);
      finally
        MyPicture.Free;
      end;
    end;

Direct pixel access

To do directly access the pixels of bitmaps one can either use external libraries, such as BGRABitmap, LazRGBGraphics and Graphics32 or use the Lazarus native TLazIntfImage. For a comparison of pixel access methods, see fast direct pixel access.

On some Lazarus widgetsets (notably LCL-Gtk2), the bitmap data is not stored in memory location which can be accessed by the application and in general the LCL native interfaces draw only through native Canvas routines, so each SetPixel / GetPixel operation involves a slow call to the native Canvas API. In LCL-CustomDrawn this is not the case since the bitmap is locally stored for all backends and SetPixel / GetPixel is fast. For obtaining a solution which works in all widgetsets one should use TLazIntfImage. As Lazarus is meant to be platform independent and work in gtk2, the TBitmap class does not provide a property like Scanline. There is a GetDataLineStart function, equivalent to Scanline, but only available for memory images like TLazIntfImage which internally uses TRawImage.

To sum it up, with the standard TBitmap, you can only change pixels indirectly, by using TCanvas.Pixels. Calling a native API to draw / read an individual pixel is course slower than direct pixel access, notably so in LCL-gtk2 and LCL-Carbon.

컬러가 투명한 비트맵 그리기

��루스 0.9.11�서 구현� 새로운 특징� 컬러 투명한 비트맵�다. 비트맵 파�(*.BMP)파�� 투명�를 저장 할 수 있는 어떠한 정보� 저장할 수 없지만, 투명�역� 표현하기위한 컬러를 선�한다면 그 정보를 가진 것 처럼 �작한다. �것� Win32 어플리케�션�서 사용� �반�� 트릭�다.

다� 예제는 윈�우즈 리소스�서 비트맵� 로드하고, 투명하기 �하는 색�(clFuchsia)� 선�하고 그것� 캔버스� 그린다.

pascal
procedure MyForm.MyButtonOnClick(Sender: TObject);
    var
      buffer: THandle;
      bmp: TBitmap;
      memstream: TMemoryStream;
    begin
      bmp := TBitmap.Create;
    
      buffer := Windows.LoadBitmap(hInstance, MAKEINTRESOURCE(ResourceID));
    
      if (buffer = 0) then exit; // 비트맵� 로딩하다가 �러
    
      bmp.Handle := buffer;
      memstream := TMemoryStream.create;
      try
        bmp.SaveToStream(memstream);
        memstream.position := 0;
        bmp.LoadFromStream(memstream);
      finally
        memstream.free;
      end;
    
      bmp.Transparent := True;
      bmp.TransparentColor := clFuchsia;
    
      MyCanvas.Draw(0, 0, bmp);
    
      bmp.Free; // 할당� 비트맵� 해제한다.
    end;

메모리 할당� TMemoryStream으로 수행한다는 것� 명심하�. �미지를 정확히 로딩하는지 확�하는 것� 필수�다.

스�린� 스�린 샷 얻기

��루스 0.9.16 �래�로스 플랫���서 스�린� 스�린샷� 얻기 위해 LCL� 사용할 수 있다. 다� 예제 코드가 그렇게 한다(gtk2와 win32��서 �작하지만, gtk1�서는 현재 �작하지 않는다):

pascal
uses LCLIntf, LCLType;
    
      ...
    
    var
      MyBitmap: TBitmap;
      ScreenDC: HDC;
    begin
      MyBitmap := TBitmap.Create;
      ScreenDC := GetDC(0);
      MyBitmap.LoadFromDevice(ScreenDC);
      ReleaseDC(ScreenDC);
    
      ...

서서히 사�지는 예

Fading 그림� 만들려고 한다면, �파��서는 다�과 같� 것�다:

`

pascal
type
      PRGBTripleArray = ^TRGBTripleArray;
      TRGBTripleArray = array[0..32767] of TRGBTriple;
    
    procedure TForm1.FadeIn(aBitMap: TBitMap);
    var
      Bitmap, BaseBitmap: TBitmap;
      Row, BaseRow: PRGBTripleArray;
      x, y, step: integer;
    begin
      Bitmap := TBitmap.Create;
      try
        Bitmap.PixelFormat := pf32bit;  //  pf24bit
        Bitmap.Assign(aBitMap);
        BaseBitmap := TBitmap.Create;
        try
          BaseBitmap.PixelFormat := pf32bit;
          BaseBitmap.Assign(Bitmap);
          for step := 0 to 32 do begin
            for y := 0 to (Bitmap.Height - 1) do begin
              BaseRow := BaseBitmap.Scanline[y];
              Row := Bitmap.Scanline[y];
              for x := 0 to (Bitmap.Width - 1) do begin
                Row[x].rgbtRed := (step * BaseRow[x].rgbtRed) shr 5;
                Row[x].rgbtGreen := (step * BaseRow[x].rgbtGreen) shr 5; // Fading
                Row[x].rgbtBlue := (step * BaseRow[x].rgbtBlue) shr 5;
              end;
            end;
            Form1.Canvas.Draw(0, 0, Bitmap);
            InvalidateRect(Form1.Handle, nil, False);
            RedrawWindow(Form1.Handle, nil, 0, RDW_UPDATENOW);
          end;
        finally
          BaseBitmap.Free;
        end;
      finally
        Bitmap.Free;
      end;
    end;
pascal

`` ��루스�서 � 함수는 다�과 같� 구현�다:

uses LCLType, // HBitmap 타입 IntfGraphics, // TLazIntfImage 타입 fpImage; // TFPColor 타입 ... procedure TForm1.FadeIn(ABitMap: TBitMap); var SrcIntfImg, TempIntfImg: TLazIntfImage; ImgHandle,ImgMaskHandle: HBitmap; FadeStep: Integer; px, py: Integer; CurColor: TFPColor; TempBitmap: TBitmap; begin SrcIntfImg:=TLazIntfImage.Create(0,0); SrcIntfImg.LoadFromBitmap(ABitmap.Handle,ABitmap.MaskHandle); TempIntfImg:=TLazIntfImage.Create(0,0); TempIntfImg.LoadFromBitmap(ABitmap.Handle,ABitmap.MaskHandle); TempBitmap:=TBitmap.Create; for FadeStep:=1 to 32 do begin for py:=0 to SrcIntfImg.Height-1 do begin for px:=0 to SrcIntfImg.Width-1 do begin CurColor:=SrcIntfImg.Colors[px,py]; CurColor.Red:=(CurColor.RedFadeStep) shr 5; CurColor.Green:=(CurColor.GreenFadeStep) shr 5; CurColor.Blue:=(CurColor.Blue*FadeStep) shr 5; TempIntfImg.Colors[px,py]:=CurColor; end; end; TempIntfImg.CreateBitmaps(ImgHandle,ImgMaskHandle,false); TempBitmap.Handle:=ImgHandle; TempBitmap.MaskHandle:=ImgMaskHandle; Canvas.Draw(0,0,TempBitmap); end; SrcIntfImg.Free; TempIntfImg.Free; TempBitmap.Free; end;

pascal

ì�´ 페ì�´ì§€ì�˜ ë�¼ìž�루스 코드는 $LazarusPath/examples/lazintfimage/fadein1.lpi 프로ì �트ì—�서 가져온 것ì�´ë‹¤. 그러므로 만약 잘하고 ì‹ë‹¤ë©´ ì�´ 예제를 ìž�세히 ë³´ê³  그래픽 프로그래ë°�ì�„ 시작하ë�¼. 

### TLazIntfImage를 Canvas� 그리기

ScanLines �성 �시�으로 TBitmap�서 삭제 �었기 때문�, Bitmap scanline ��터� 접근하기 위한 유�한 방법� TLazIntfImage를 사용하는 것�다. 다�� TBitmap�서 TLazIntfImage � �성하는 방법� 대한 것과 Canvas� TLazIntfImage� 그리는 방법� 대한 예�다.

uses ...GraphType, IntfGraphics, LCLType, LCLProc, LCLIntf ...

pascal
procedure TForm1.Button4Click(Sender: TObject);
var
  b: TBitmap;
  t: TLazIntfImage;
  bmp, old: HBitmap;
  msk: HBitmap;
  tmpDC: HDC;
begin
  b := TBitmap.Create;
  try
    b.LoadFromFile('test.bmp');
    t := b.CreateIntfImage;
    t.CreateBitmaps(bmp, msk, false);
pascal
tmpDC := CreateCompatibleDC(Canvas.Handle);
old := SelectObject(tmpDC, bmp);
BitBlt(Canvas.Handle, 0, 0, t.Width, t.Height, tmpDC, 0, 0, SRCCOPY);
DeleteObject(SelectObject(tmpDC, old));
DeleteObject(msk);
DeleteDC(tmpDC);
pascal
finally
  t.Free;
  b.Free;
end;
pascal
end;
pascal

## Working with TLazIntfImage, TRawImage and TLazCanvas

TLazIntfImage is a non-native equivalent of TRasterImage (more commonly utilized in the form of it's descendent TBitmap). The first thing to be aware about this class is that unlike TBitmap it will not automatically allocate a memory area for the bitmap, one should first initialize a memory area and then give it to the TLazIntfImage. Right after creating a TLazIntfImage one should either connect it to a TRawImage or load it from a TBitmap. 

TRawImage is of the type object and therefore does not need to be created nor freed. It can either allocate the image memory itself when one calls TRawImage.CreateData or one can pass a memory block allocated for examply by a 3rd party library such as the Windows API of the Cocoa Framework from Mac OS X and pass the information of the image in TRawImage.Description, TRawImage.Data and TRawImage.DataSize. Instead of attaching it to a RawImage one could also load it from a TBitmap which will copy the data from the TBitmap and won't be syncronized with it afterwards. The TLazCanvas cannot exist alone and must always be attached to a TLazIntfImage. 

The example below shows how to choose a format for the data and ask the TRawImage to create it for us and then we attach it to a TLazIntfImage and then attach a TLazCanvas to it:

uses graphtype, intfgraphics, lazcanvas;

pascal
var
  AImage: TLazIntfImage;
  ACanvas: TLazCanvas;
  lRawImage: TRawImage;
begin
    lRawImage.Init;
    lRawImage.Description.Init_BPP32_A8R8G8B8_BIO_TTB(AWidth, AHeight);
    lRawImage.CreateData(True);
    AImage := TLazIntfImage.Create(0,0);
    AImage.SetRawImage(lRawImage);
    ACanvas := TLazCanvas.Create(AImage);
pascal

### Initializing a TLazIntfImage

One cannot simply create an instance of TLazIntfImage and start using it. It needs to add a storage to it. There are 3 ways to do this: 

1\. Attach it to a TRawImage 

2\. Load it from a TBitmap. Note that it will copy the memory of the TBitmap so it won't remain connected to it.

SrcIntfImg:=TLazIntfImage.Create(0,0); SrcIntfImg.LoadFromBitmap(ABitmap.Handle,ABitmap.MaskHandle);

pascal

3\. Load it from a raw image description, like this:

IntfImg := TLazIntfImage.Create(0,0); IntfImg.DataDescription:=GetDescriptionFromDevice(0); IntfImg.SetSize(10,10);

pascal

The 0 device in **GetDescriptionFromDevice(0)** uses the current screen format. 

### TLazIntfImage.LoadFromFile

Here is an example how to load an image directly into a TLazIntfImage. It initializes the TLazIntfImage to a 32bit RGBA format. Keep in mind that this is probably not the native format of your screen.

uses LazLogger, Graphics, IntfGraphics, GraphType; procedure TForm1.FormCreate(Sender: TObject); var AImage: TLazIntfImage; lRawImage: TRawImage; begin // create a TLazIntfImage with 32 bits per pixel, alpha 8bit, red 8 bit, green 8bit, blue 8bit, // Bits In Order: bit 0 is pixel 0, Top To Bottom: line 0 is top lRawImage.Init; lRawImage.Description.Init_BPP32_A8R8G8B8_BIO_TTB(0,0); lRawImage.CreateData(false); AImage := TLazIntfImage.Create(0,0); try AImage.SetRawImage(lRawImage); // Load an image from disk. // It uses the file extension to select the right registered image reader. // The AImage will be resized to the width, height of the loaded image. AImage.LoadFromFile('lazarus/examples/openglcontrol/data/texture1.png'); debugln(['TForm1.FormCreate ',AImage.Width,' ',AImage.Height]); finally AImage.Free; end; end;

pascal

### Loading a TLazIntfImage into a TImage

The pixel data of a **TImage** is the **TImage.Picture** property, which is of type _TPicture_. **TPicture** is a multi format container containing one of several common image formats like Bitmap, Icon, Jpeg or PNG . Usually you will use the _TPicture.Bitmap_ to load a **TLazIntfImage** :

Image1.Picture.Bitmap.LoadFromIntfImage(IntfImg);

pascal

**Notes:**

  * To load a **transparent** TLazIntfImage you have to set the **Image1.Transparent** to true.
  * TImage uses the screen format. If the TLazIntfImage has a different format then the pixels will be converted. Hint: You can use **IntfImg.DataDescription:=GetDescriptionFromDevice(0);** to initialize the TLazIntfImage with the screen format.

### 서서히 사�지는 예제

TLazIntfImage를 �용한 서서히 사�지는 예제

{ This code has been taken from the $LazarusPath/examples/lazintfimage/fadein1.lpi project. } uses LCLType, // HBitmap 타입 IntfGraphics, // TLazIntfImage 타입 fpImage; // TFPColor 타입 ... procedure TForm1.FadeIn(ABitMap: TBitMap); var SrcIntfImg, TempIntfImg: TLazIntfImage; ImgHandle,ImgMaskHandle: HBitmap; FadeStep: Integer; px, py: Integer; CurColor: TFPColor; TempBitmap: TBitmap; begin SrcIntfImg:=TLazIntfImage.Create(0,0); SrcIntfImg.LoadFromBitmap(ABitmap.Handle,ABitmap.MaskHandle); TempIntfImg:=TLazIntfImage.Create(0,0); TempIntfImg.LoadFromBitmap(ABitmap.Handle,ABitmap.MaskHandle); TempBitmap:=TBitmap.Create; for FadeStep:=1 to 32 do begin for py:=0 to SrcIntfImg.Height-1 do begin for px:=0 to SrcIntfImg.Width-1 do begin CurColor:=SrcIntfImg.Colors[px,py]; CurColor.Red:=(CurColor.RedFadeStep) shr 5; CurColor.Green:=(CurColor.GreenFadeStep) shr 5; CurColor.Blue:=(CurColor.Blue*FadeStep) shr 5; TempIntfImg.Colors[px,py]:=CurColor; end; end; TempIntfImg.CreateBitmaps(ImgHandle,ImgMaskHandle,false); TempBitmap.Handle:=ImgHandle; TempBitmap.MaskHandle:=ImgMaskHandle; Canvas.Draw(0,0,TempBitmap); end; SrcIntfImg.Free; TempIntfImg.Free; TempBitmap.Free; end;

pascal

### Image format specific example

If you know that the TBitmap is using blue 8bit, green 8bit, red 8bit you can directly access the bytes, which is somewhat faster:

uses LCLType, // HBitmap type IntfGraphics, // TLazIntfImage type fpImage; // TFPColor type ... type TRGBTripleArray = array[0..32767] of TRGBTriple; PRGBTripleArray = ^TRGBTripleArray;

pascal
procedure TForm1.FadeIn2(aBitMap: TBitMap);
 var
   IntfImg1, IntfImg2: TLazIntfImage;
   ImgHandle,ImgMaskHandle: HBitmap;
   FadeStep: Integer;
   px, py: Integer;
   CurColor: TFPColor;
   TempBitmap: TBitmap;
   Row1, Row2: PRGBTripleArray;
 begin
   IntfImg1:=TLazIntfImage.Create(0,0);
   IntfImg1.LoadFromBitmap(aBitmap.Handle,aBitmap.MaskHandle);
pascal
IntfImg2:=TLazIntfImage.Create(0,0);
IntfImg2.LoadFromBitmap(aBitmap.Handle,aBitmap.MaskHandle);
pascal
TempBitmap:=TBitmap.Create;
pascal
//with Scanline-like
for FadeStep:=1 to 32 do begin
  for py:=0 to IntfImg1.Height-1 do begin
    Row1 := IntfImg1.GetDataLineStart(py); //like Delphi TBitMap.ScanLine
    Row2 := IntfImg2.GetDataLineStart(py); //like Delphi TBitMap.ScanLine
    for px:=0 to IntfImg1.Width-1 do begin
      Row2^[px].rgbtRed:= (FadeStep * Row1^[px].rgbtRed) shr 5;
      Row2^[px].rgbtGreen := (FadeStep * Row1^[px].rgbtGreen) shr 5; // Fading
      Row2^[px].rgbtBlue := (FadeStep * Row1^[px].rgbtBlue) shr 5;
    end;
  end;
  IntfImg2.CreateBitmaps(ImgHandle,ImgMaskHandle,false);
pascal
TempBitmap.Handle:=ImgHandle;
TempBitmap.MaskHandle:=ImgMaskHandle;
Canvas.Draw(0,0,TempBitmap);
pascal
end;
pascal
IntfImg1.Free;
IntfImg2.Free;
TempBitmap.Free;
pascal
end;
pascal

### Conversion between TLazIntfImage and TBitmap

Since Lazarus has no TBitmap.ScanLines property, the best way to access the pixels of an image in a fast way for both reading and writing is by using TLazIntfImage. The TBitmap can be converted to a TLazIntfImage by using TBitmap.CreateIntfImage() and after modifying the pixels it can be converted back to a TBitmap by using TBitmap.LoadFromIntfImage(); Here's the sample on how to create TLazIntfImage from TBitmap, modify it and then go back to the TBitmap.

uses ...GraphType, IntfGraphics, LCLType, LCLProc, LCLIntf ...

pascal
procedure TForm1.Button4Click(Sender: TObject);
var
  b: TBitmap;
  t: TLazIntfImage;
begin
  b := TBitmap.Create;
  try
    b.LoadFromFile('test.bmp');
    t := b.CreateIntfImage;
pascal
// Read and/or write to the pixels
t.Colors[10,20] := colGreen;
pascal
b.LoadFromIntfImage(t);
pascal
finally
  t.Free;
  b.Free;
end;
pascal
end;
pascal

### Using the non-native StretchDraw from LazCanvas

Just like TCanvas.StretchDraw there is TLazCanvas.StretchDraw but you need to specify the interpolation which you desire to use. The interpolation which provides a Windows-like StretchDraw with a very sharp result (the opposite of anti-aliased) can be added with: TLazCanvas.Interpolation := TFPSharpInterpolation.Create; 

There are other interpolations available in the unit fpcanvas.

uses intfgraphics, lazcanvas;

pascal
procedure TForm1.StretchDrawBitmapToBitmap(SourceBitmap, DestBitmap: TBitmap; DestWidth, DestHeight: integer);
var
  DestIntfImage, SourceIntfImage: TLazIntfImage;
  DestCanvas: TLazCanvas;
begin
  // Prepare the destination
pascal
DestIntfImage := TLazIntfImage.Create(0, 0);
DestIntfImage.LoadFromBitmap(DestBitmap.Handle, 0);
pascal
DestCanvas := TLazCanvas.Create(DestIntfImage);
pascal
//Prepare the source
SourceIntfImage := TLazIntfImage.Create(0, 0);
SourceIntfImage.LoadFromBitmap(SourceBitmap.Handle, 0);
pascal
// Execute the stretch draw via TFPSharpInterpolation
DestCanvas.Interpolation := TFPSharpInterpolation.Create;
DestCanvas.StretchDraw(0, 0, DestWidth, DestHeight, SourceIntfImage);
pascal
// Reload the image into the TBitmap
DestBitmap.LoadFromIntfImage(DestIntfImage);
pascal
SourceIntfImage.Free;
DestCanvas.Interpolation.Free;  
DestCanvas.Free;
DestIntfImage.Free;
pascal
end;
pascal
procedure TForm1.FormPaint(Sender: TObject);
var
  Bmp, DestBitmap: TBitmap;
begin
  // Prepare the destination
  DestBitmap := TBitmap.Create;
  DestBitmap.Width := 100;
  DestBitmap.Height := 100;
pascal
Bmp := TBitmap.Create;
Bmp.Width := 10;
Bmp.Height := 10;
Bmp.Canvas.Pen.Color := clYellow;
Bmp.Canvas.Brush.Color := clYellow;
Bmp.Canvas.Rectangle(0, 0, 10, 10);
StretchDrawBitmapToBitmap(Bmp, DestBitmap, 100, 100);
Canvas.Draw(0, 0, Bmp);
Canvas.Draw(100, 100, DestBitmap);
pascal
end;
pascal

## 모션 그래픽 - 플리커�� 피하는 방법

ë§Žì�€ 프로그램ì�´ 2D 그래픽ì�„ GUIì—� ìœë ¥í•˜ì—¬ 그린다. ì�´ 그래픽ì�„ 빨리 변환하고ìž� 한다면 ê³§ 문제ì—� 봉착할 것ì�´ë‹¤: 빠르게 변환하는 그래픽ì�€ 종종 스í�¬ë¦°ì�„ 번ì©�ì�´ê²Œ 한다. ì�´ëŸ¬í•œ ìƒ�황ì�€ ê°€ë�” ì „ì²´ ì�´ë¯¸ì§€ë¥¼ 보거나 ê°€ë�”ì�€ ë€ë„ì �으로 그려질 때 ì�¼ì–´ë‚œë‹¤. ì�´ëŠ” 그림ì�„ 그리는 시간ì�´ 필요하기 때문ì—� ì�¼ì–´ë‚˜ëŠ” 것ì�´ë‹¤. 

하지만 번�임� 어떻게 피하고 최�� 드로잉 ��를 얻� 수 있�까? 물론 OpenGL� �용한 하드웨어 가� 기능� 사용할 수 있지만, �러한 접근법� 작� 프로그램 �는 구형 컴퓨터�서는 꽤 어려운 문제가 �기� 한다. OpenGL� �움� 받는다면 ��루스� 딸려오는 예제를 살펴보면 �다. �한 A.J. Venter� gamepack를 사용할 수 있는�, �블 버� 캔버스와 스프��트 컴�넌트를 제공한다. 

Canvas� 그리기 위해서는 제공�는 옵션 등� �제 시험해 볼 것�다: 

  * TImage� 그리기
  * �, TPaintBox �는 다른 컨트롤� OnPaint� 그리기
  * �체�으로 그릴 수 있는 커스텀 컨트롤 �성하기
  * A.J. Venter� 게임팩 사용하기

### TImage� 그리기

TImage는 �개 파트로 구성�다. TGraphic, 종종 TBitmap,� �구�� 그림과 비주얼 �역� 가지며 OnPaint 때마다 다시 그려진다. TImage� �기를 바꾸면 bitmap� �기를 바꾸지 **않는다**. 그래픽(�는 비트맵)� Image1.Picture.Graphic (�는 Image1.Picture.Bitmap)� 통해 접근할 수 있다. 캔버스는 Image1.Picture.Bitmap.Canvas�다. TImage� 비주얼 �역� 캔버스는 Image1.Canvas를 통해 Image1.OnPaint �안�만 접근 할 수 있다. 

**중요** : TImage� graphic/bitmap� 그리기 위해 Image1 �벤트� OnPaint를 사용하면 안�다. TImage� graphic� 버�� 보관 �므로, 하고� 하는 모든 것� 어� 곳�서�지 그려지고 변화는 �구�� 것� �다. 그러나 만약 항� 다시 그린다면 �미지는 번��게 � 것�다. �런 경우 다른 옵션� 시�해야 한다. TImage� 그리는 것� 다른 접근법보다 �리다고 여겨진다. 

#### TImage� 비트맵� �기 변경

Note: OnPaint�안 �것� 사용하지 마�.

with Image1.Picture.Bitmap do begin Width:=100; Height:=120; end;

pascal

#### TImage� 비트맵� 페�팅하기

Note: OnPaint�안 �것� 사용하지 마�.

with Image1.Picture.Bitmap.Canvas do begin // 모든 비트맵� 빨강으로 채우기 Brush.Color:=clRed; FillRect(0,0,Width,Height); end;

pascal

Note: Image1.OnPaintì�˜ ë‚´ë€ì—�서 Image1.Canvasì�€ volatile visible ì˜�ì—­ì�„ 가리킨다. Image1.OnPaintì�˜ 외ë€ì—�서는 Image1.Canvas는 Image1.Picture.Bitmap.Canvas를 가리킨다. 

다른 예: 

` `

`

procedure TForm1.BitBtn1Click(Sender: TObject); var x, y: Integer; begin // 배경 그리기 MyImage.Canvas.Pen.Color := clWhite; MyImage.Canvas.Rectangle(0, 0, Image.Width, Image.Height);

pascal
// 사�형 그리기
MyImage.Canvas.Pen.Color := clBlack;
for x := 1 to 8 do
 for y := 1 to 8 do
  MyImage.Canvas.Rectangle(Round((x - 1) * Image.Width / 8), Round((y - 1) * Image.Height / 8),
     Round(x * Image.Width / 8), Round(y * Image.Height / 8));
pascal
end;
pascal

``

TImage� volatile visual �역� 페�팅하기

OnPaint �안 � �역�만 페�트 할 수 있다. 그 �역� 무효화 � 때 결국 LCL� ��으로 OnPaint를 부른다. Image1.Invalidate로 수��으로 그 여역� 무효화 시킬 수 있다.�는 즉시 OnPaint를 부르는 것� 아니므로 �할 때마다 Invalidate를 부를 수 있다.

pascal
procedure TForm.Image1Paint(Sender: TObject);
     begin
       with Image1.Canvas do begin
         // 선� 페�트한다.
         Pen.Color:=clRed;
         Line(0,0,Width,Height);
       end;
     end;

OnPaint �벤트� 그리기

� 경우 모든 드로잉� �� OnPaint �벤트�서 �루어져야 한다. TImage 처럼 버�� 남아있지 않는다.

�체�으로 그릴 수 있는 커스텀 컨트롤 �성하기

커스텀 컨트롤� �성하는 것� 코드를 구조화 시키는 장�� 있으며 컨트롤� 재사용할 수 있다. � 접근 법� 매우 빠르지만 TBitmap� 먼저 그리지 않고 캔버스� 그린다면 여전히 번�임� 나타날 것�다. �러한 경우 컨트롤� OnPaint �벤트를 사용할 필요가 없다.

다�� 커스텀 컨트롤� 대한 예제�다:

`

pascal
uses
     Classes, SysUtils, Controls, Graphics, LCLType;
    
    type
      TMyDrawingControl = class(TCustomControl)
      public
        procedure EraseBackground(DC: HDC); override;
        procedure Paint; override;
      end;
    
    implementation
    
    procedure TMyDrawingControl.EraseBackground(DC: HDC);
    begin
      // 디�트 배경 지우기를 가능하게 하려면 다�� 코멘트를 지워�
      //inherited EraseBackground(DC);
    end; 
    
    procedure TMyDrawingControl.Paint;
    var
      x, y: Integer;
      Bitmap: TBitmap;
    begin
      Bitmap := TBitmap.Create;
      try
        // Bitmap �기 초기화
        Bitmap.Height := Height;
        Bitmap.Width := Width;
     
        // 배경 그리기
        Bitmap.Canvas.Pen.Color := clWhite;
        Bitmap.Canvas.Rectangle(0, 0, Width, Height);
    
        // 사�형 그리기
        Bitmap.Canvas.Pen.Color := clBlack;
        for x := 1 to 8 do
         for y := 1 to 8 do
          Bitmap.Canvas.Rectangle(Round((x - 1) * Width / 8), Round((y - 1) * Height / 8),
           Round(x * Width / 8), Round(y * Height / 8));
          
        Canvas.Draw(0, 0, Bitmap);
      finally
        Bitmap.Free;
      end;
    
      inherited Paint;
    end;
pascal

``

그리고 그것� ��� �성하는 방법�다: 

` `

`

procedure TMyForm.FormCreate(Sender: TObject); begin MyDrawingControl:= TMyDrawingControl.Create(Self); MyDrawingControl.Height := 400; MyDrawingControl.Width := 500; MyDrawingControl.Top := 0; MyDrawingControl.Left := 0; MyDrawingControl.Parent := Self; MyDrawingControl.DoubleBuffered := True; end;

pascal

``

해제하는 것� 잊으면 안�다:

`

pascal
procedure TMyForm.FormDestroy(Sender: TObject);
    begin
      MyDrawingControl.Free;
    end;
pascal

``

�것� 표준 위치� 있기 때문�, Top과 Left를 0으로 설정할 필요는 없지만, 컨트롤� 놓� 곳� 지정하기 위해서는 그렇게 해야 한다. 

"MyDrawingControl.Parent := Self;" 는 메우 중요하므로 그렇게 하지 않는다면 컨트롤� 볼 수 없� 것�다. 

"MyDrawingControl.DoubleBuffered := True;"� 윈�우�서 번�임� 피할려면 필요하다. gtk�서는 �작하지 않는다. 

### A.J. Venter� 게임팩 사용하기

게임팩 접근법� 한개� �블 버�� 캔버스� 모든 것� 그리는 것으로, 준비�, 보여지는 캔버스만 업��트 �다. �것� 매우 짧� 코드로 구현�지만, 많� 수� 스프��트가 넓� 범위�서 빠르게 변화하는 장면� 가능하게 해주는 잇�� 있다. �러한 접근법� 사용하려면,A.J. Venter� gamepack� 관심� 있� 것�다. �는 ��우스�서 게임� 개발할 수 있는 게임 컴�넌트로서 스프��트 컴�넌트�만� 아니� �블-버� 디스플레� �역� 제공해 주며 서로 서로 잘 통합��� 디�� �었다. 게임팩� subversion:  
� 통해 구할 수 있다. 

` svn co <svn://silentcoder.co.za/lazarus/gamepack> ` 추가�� 정보와 문서 그리고 다운로드는 [홈페�지](<http://outkastsolutions.co.za/outkast/index.php?option=com_openwiki&Itemid=&id=gamepack>)�서 구할 수 있다. 

## �미지 �맷

� �미지 �맷� 사용하기 위한 �당한 �래스� 테�블� 여기 있다. 

�맷  | �미지 �래스  | 유닛   
---|---|---  
커서(cur) | TCursor | Graphics   
비트맵(bmp) | TBitmap | Graphics   
윈�우즈 아�콘 (ico) | TIcon | Graphics   
Mac OS X 아�콘(icns) | TicnsIcon | Graphics   
Pixmap (xpm) | TPixmap | Graphics   
Portable Network Graphic (png) | TPortableNetworkGraphic | Graphics   
JPEG (jpg, jpeg) | TJpegImage | Graphics   
PNM (pnm) | TPortableAnyMapGraphic | Graphics   
  
[[fcl-image|fcl-image 지� �맷]] 리스트를 보세요. 

### �맷 변환

ê°€ë�” 그래픽 í�¬ë§·ì�„ 다른 형ì‹�으로 변환해야 í•  때가 있다. 한가지 방법ì�€ 그래픽ì�„ 중간 형ì‹�으로 바꾼 후 TBitmap으로 변환하는 것ì�´ë‹¤. 대ë€ë„ì�˜ í�¬ë§·ì�€ TBitmapì—�서 만들어질 수 있다. 

Bitmap� PNG로 변환하고 파�� 저장하는 것:

procedure SaveToPng(const bmp: TBitmap; PngFileName: String); var png : TPortableNetworkGraphic; begin png := TPortableNetworkGraphic.Create; try png.Assign(bmp); png.SaveToFile(PngFileName); finally png.Free; end; end;

pascal

## 픽셀 �맷

### TColor

LCLì—�서 TColor를 위한 ë‚´ë€ í”½ì…€ í�¬ë§·ì�€ XXBBGGRR í�¬ë§·ìœ¼ë¡œ 네ì�´í‹°ë¸Œ 윈ë�„우즈 í�¬ë§·ì—� 대ì�‘하며 AARRGGBB를 사용하는 대ë€ë„ì�˜ 다른 ë�¼ì�´ë¸ŒëŸ¬ë¦¬ì™€ëŠ” 반대ì�´ë‹¤. XX 파트는 컬러가 fixed 컬러ì�¸ì§€ 확ì�¸í•˜ëŠ”ë�° 사용하며 ì�´ê²½ìš° XX는 00ì�´ì–´ì•¼ 하고, 시스템 컬러ì�˜ ì�¸ë�±ìФì�¸ì§€ 확ì�¸í•œë‹¤. 알파 채ë„�ì�„ 위한 공간ì�€ 예약ë�˜ì–´ì§€ì§€ 않았다. 

ë„리ë�œ RGB 채ë„�ì�„ TColor로 변환하기 위해서는 다ì�Œì�„ 사용한다:

RGBToColor(RedVal, GreenVal, BlueVal);

pascal

TColor� ��� 채�� 얻으려면 변수는 Red, Green � Blue 함수� 사용한다:

RedVal := Red(MyColor); GreenVal := Green(MyColor); BlueVal := Blue(MyColor);

pascal

### TFPColor

TFPColor는 대ë€ë„ì�˜ ë�¼ì�´ë¸ŒëŸ¬ì—�서 ì�¼ë°˜ì �ì�¸ AARRGGBB í�¬ë§·ì�„ 사용한다. 

## LCL 없� 그리기

LCL ì—†ì�´ 그릴 수 있다. 예를 들어 웹서버ì—�서 ë�Œì•„가는 프로그램ì�´ 만든 그래픽ì�€ 완전한 비주얼 ë�¼ì�´ë¸ŒëŸ¬ë¦¬ê°€ 없어ë�„ ë�™ìž‘해야 한다. ì�´ë¥¼ 위해 FPImage(별명ì�€ fcl-image)를 사용할 수 있다, ì�´ëŠ” 파스칼로 작성ë�œ 매우 ì�¼ë°˜ì �ì�¸ ì�´ë¯¸ì§€ì�´ë©° 드로잉 ë�¼ì�´ë¸ŒëŸ¬ë¦¬ì�´ë‹¤. 사실 LCLì�€ 역시 FPImage를 사용하고 위젯셋(winapi, gtk, carbon, ...)ì�˜ 호ìœì�„ 통해 드로임 함수를 구현한다. 

여기� 200x100 �미지를 �성하고 백색으로 배경� 칠하며 몇몇 �스트를 쓰고 .png로 저장하는 방법� 관한 예가 있다:

program fontdraw;

pascal
{$mode objfpc}{$H+}
pascal
uses
  Classes, SysUtils, FPimage, FPImgCanv, ftfont, FPWritePNG, FPCanvas;
pascal
procedure TestFPImgFont;
var
  Img: TFPMemoryImage;
  Writer: TFPWriterPNG;
  ms: TMemoryStream;
  ImgCanvas: TFPImageCanvas;
  fs: TFileStream;
  AFont: TFreeTypeFont;
begin
  Img:=nil;
  ImgCanvas:=nil;
  Writer:=nil;
  ms:=nil;
  fs:=nil;
  AFont:=nil;
  try
    // 프리타입 �트 매니저 초기화
    ftfont.InitEngine;
    FontMgr.SearchPath:='/usr/share/fonts/truetype/ttf-dejavu/';
    AFont:=TFreeTypeFont.Create;
pascal
// � 200, 높� 100� �미지 �성
Img:=TFPMemoryImage.Create(200,100);
Img.UsePalette:=false;
// 드로잉 �작� 통해 캔버스 �성
ImgCanvas:=TFPImageCanvas.create(Img);
pascal
// 하얀 배경 칠함
ImgCanvas.Brush.FPColor:=colWhite;
ImgCanvas.Brush.Style:=bsSolid;
ImgCanvas.Rectangle(0,0,Img.Width,Img.Height);
pascal
// �스트 그리기
ImgCanvas.Font:=AFont;
ImgCanvas.Font.Name:='DejaVuSans';
ImgCanvas.Font.Size:=20;
ImgCanvas.TextOut(10,30,'Test');
pascal
// 메모리 스트림� png로 �미지 쓰기
Writer:=TFPWriterPNG.create;
ms:=TMemoryStream.Create;
writer.ImageWrite(ms,Img);
// 메모리 스트림� 파�� 쓰기
ms.Position:=0;
fs:=TFileStream.Create('testfont.png',fmCreate);
fs.CopyFrom(ms,ms.Size);
pascal
finally
  AFont.Free;
  ms.Free;
  Writer.Free;
  ImgCanvas.Free;
  Img.Free;
  fs.Free;
end;
pascal
end;
pascal
begin
  TestFPImgFont;
end.
pascal

  * [[Free Pascal Tutorial|파스칼 튜토리얼]] \- [Tao Yue's](<http://www.taoyue.com/>) [Pascal Tutorial](<http://www.taoyue.com/tutorials/pascal/>)
  * [[Free Pascal videos|Free Pascal video tutorials]]

---
*From the Free Pascal wiki, page "Developing with Graphics/ko", as the Internet Archive kept it on 2025-02-19, last changed on 2020-02-09. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*