Difference between revisions of "BGRABitmap/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 43: Line 43:
 
Двойная буферизация на самом деле не является частью BGRABitmap, потому что она больше о том, как обрабатывать формы. Для двойной буферизации вы можете использовать TBGRAVirtualScreen, который находится в пакете [[BGRAControls]]. Кроме того, двойная буферизация в BGRABitmap работает как любая двойная буферизация. Вам нужно иметь растровое изображение, в котором вы храните свой чертеж и которое вы отображаете с помощью одной инструкции Draw.
 
Двойная буферизация на самом деле не является частью BGRABitmap, потому что она больше о том, как обрабатывать формы. Для двойной буферизации вы можете использовать TBGRAVirtualScreen, который находится в пакете [[BGRAControls]]. Кроме того, двойная буферизация в BGRABitmap работает как любая двойная буферизация. Вам нужно иметь растровое изображение, в котором вы храните свой чертеж и которое вы отображаете с помощью одной инструкции Draw.
  
====Ссылка на модули BGRABitmapTypes====
+
====Ссылка на модули типов BGRABitmap====
  
 
* [[BGRABitmap Pixel types|Pixel types and functions]]: ''TBGRAPixel'', ''THSLAPixel''...
 
* [[BGRABitmap Pixel types|Pixel types and functions]]: ''TBGRAPixel'', ''THSLAPixel''...
* [[BGRABitmap Types imported from Graphics|Types imported from Graphics]]: ''TColor'', pen style...
+
* [[BGRABitmap Types imported from Graphics|Types imported from Graphics]]: ''TColor'', стиль пера...
 
* [[BGRABitmap Color definitions|Color definitions]]: ''VGAColors'', ''CSSColors''...
 
* [[BGRABitmap Color definitions|Color definitions]]: ''VGAColors'', ''CSSColors''...
* [[BGRABitmap Geometry types|Geometry types]]: ''TPointF'', Bezier curves, ''TArcDef''...
+
* [[BGRABitmap Geometry types|Geometry types]]: ''TPointF'', кривые Берзье, ''TArcDef''...
* [[BGRABitmap Miscellaneous types|Miscellaneous types]]: font, image format, resampling...
+
* [[BGRABitmap Miscellaneous types|Miscellaneous types]]: шрифт, формат изображения, ресэмплинг...
* [[TBGRACustomBitmap and IBGRAScanner]]: the base class for ''TBGRABitmap'' and scanners
+
* [[TBGRACustomBitmap and IBGRAScanner]]: базовый класс для TBGRABitmap и сканеров
  
 
==== Installation ====
 
==== Installation ====

Revision as of 00:28, 16 December 2018

Deutsch (de) English (en) español (es) français (fr) русский (ru) 中文(中国大陆)‎ (zh_CN)

bgrabitmap logo.jpg

См.также: Developing with Graphics

Описание

BGRABitmap - это набор модулей, предназначенных для изменения и создания изображений с прозрачностью (альфа-канал). Прямой пиксельный доступ позволяет быстро обрабатывать изображения. Библиотека была протестирована на Windows, Ubuntu и Mac OS X (последняя версия не работает на Mac), с наборами виджетов win32, gtk1, gtk2 и carbon.

Основным классом является TBGRABitmap, который является производным от TFPCustomImage. Существует также TBGRAPtrBitmap, позволяющий редактировать данные BGRA, которые уже распределены. Этот формат состоит из 4 байтов для каждого пикселя (синий, зеленый, красный и альфа в этом порядке).

Изображение может быть отображено на обычном Canvas или на OpenGL surface.

Дополнительные пакеты

Некоторые пакеты используют BGRABitmap для обеспечения элементов управления приятной графикой:

  • BGLControls: предоставляет TBGLVirtualScreen для рисования на поверхности OpenGL. Этот пакет находится в архиве BGRABitmap.
  • BGRAControls: ярлыки с тенями, красивыми кнопками, фигурами и т.д.
  • uE Controls: датчики, светодиоды и т.д.
  • Material Design: Компоненты пользовательского интерфейса, основанные на принципах разработки материалов Google.
  • BGRAControlsFX[1]: элементы управления рендеринга на поверхности OpenGL.

Некоторые примеры в папке с примерами используют BGRAControls и BGLControls. Вам может понадобиться установить их, чтобы открыть эти проекты в Lazarus. См. Install Packages.

Использование BGRABitmap

Руководства

Обзор

Функции имеют длинные имена, чтобы быть понятными. Почти все доступно в виде функции или с помощью свойства объекта TBGRABitmap. Например, вы можете использовать CanvasBGRA, чтобы иметь некоторые холсты, похожие на TCanvas (с прозрачностью и сглаживанием) и Canvas2D, чтобы иметь те же функции, что и HTML canvas.

Некоторые специальные функции требуют использования модулей, но они могут вам не понадобиться:

  • TBGRAMultishapeFiller иметь сглаженные соединения многоугольников в BGRAPolygon
  • TBGRATextEffect в BGRATextFX
  • 2D преобразования находятся в BGRATransform
  • TBGRAScene3D в BGRAScene3D
  • Если вам нужны слои, BGRALayers предоставляет TBGRALayeredBitmap

Двойная буферизация на самом деле не является частью BGRABitmap, потому что она больше о том, как обрабатывать формы. Для двойной буферизации вы можете использовать TBGRAVirtualScreen, который находится в пакете BGRAControls. Кроме того, двойная буферизация в BGRABitmap работает как любая двойная буферизация. Вам нужно иметь растровое изображение, в котором вы храните свой чертеж и которое вы отображаете с помощью одной инструкции Draw.

Ссылка на модули типов BGRABitmap

Installation

After unpacking a checkout, BGRA often does not compile in Linux. Try using the IDE Macro

 LCLWidgetType:=gtk2

in such cases. Still some other part may not compile.

Simple example

Create a project and open bgrabitmappackage.lpk with Lazarus. In the package window, click on "Use > Add to Project". Then in the source code of the main file (main form or main program), add to uses clause BGRABitmap units. You may need to add BGRAGraphics unit as well if you use certain types that are inherited from the LCL.

Uses 
  Classes, SysUtils, BGRABitmap, BGRABitmapTypes;

The unit BGRABitmapTypes contains common definitions, but one can declare only BGRABitmap in order to load and show a bitmap. Then, the first step is to create a TBGRABitmap object:

var
  bmp: TBGRABitmap;
begin
  bmp := TBGRABitmap.Create(100, 100, BGRABlack); // creates a 100x100 pixels image with black background

  bmp.FillRect(20, 20, 60, 60, BGRAWhite, dmSet); // draws a white square without transparency
  bmp.FillRect(40, 40, 80, 80, BGRA(0, 0, 255, 128), dmDrawWithTransparency); // draws a transparent blue square
  ...
end;

Finally to show the bitmap:

procedure TFMain.FormPaint(Sender: TObject);
begin
  bmp.Draw(Canvas, 0, 0, True); // draw the bitmap in opaque mode (faster)
end;

See a full source code in tutorial 1.

Notions

Pixels in a bitmap with transparency are stored with 4 values, here 4 bytes in the order Blue, Green, Red, Alpha. The last channel defines the level of opacity (0 signifies transparent, 255 signifies opaque), other channels define color and luminosity.

There are basically two drawing modes. The first consists in replacing the content of the pixel information, the second consists in blending the pixel already here with the new one, which is called alpha blending.

BGRABitmap functions propose 4 modes:

  • dmSet : replaces the four bytes of the drawn pixel, transparency not handled
  • dmDrawWithTransparency : draws with alphablending and with gamma correction (see below)
  • dmFastBlend or dmLinearBlend : draws with alphablending but without gamma correction (faster but entails color distortions with low intensities).
  • dmXor : apply Xor to each component including alpha (if you want to invert color but keep alpha, use BGRA(255,255,255,0) )

Integrated drawing functions

  • draw/erase pixels
  • draw a line with or without antialiasing
  • floating point coordinates
  • floating point pen width
  • rectangle (frame or fill)
  • ellipse and polygons with antialiasing
  • spline computation (rounded curve)
  • simple fill (Floodfill) or progressive fill
  • color gradient rendering (linear, radial...)
  • round rectangles
  • texts with transparency

Drawing with the Canvas

It is possible to draw with a Canvas object, with usual functions but without antialiasing. Opacity of drawing is defined by the CanvasOpacity property. This way is slower because it needs image transformations. If you can, use CanvasBGRA instead, which allows transparency and antialiasing while having the same function names as with TCanvas.

Direct access to pixels

To access pixels, there are two properties, Data and Scanline. The first gives a pointer to the first pixel of the image, and the second gives a pointer to the first pixel of a given line.

var 
  bmp: TBGRABitmap;
  p: PBGRAPixel;
  n: integer;

begin
  bmp := TBGRABitmap.Create('image.png');
  p := bmp.Data;
  for n := bmp.NbPixels-1 downto 0 do
  begin
    p^.red := not p^.red; // invert red channel
    inc(p);
  end;
  bmp.InvalidateBitmap;   // note that we have accessed pixels directly
  bmp.Draw(Canvas, 0, 0, True);
  bmp.Free;
end;

It is necessary to call the function InvalidateBitmap to rebuild the image in a next call to Draw' for example. Notice that the line order can be reverse, depending on the LineOrder property.

See also the comparison between direct pixel access methods.

Image manipulation

Available filters (prefixed with Filter) :

  • Radial blur : non directional blur
  • Motion blur : directional blur
  • Custom blur : blur according to a mask
  • Median : computes the median of colors around each pixel, which softens corners
  • Pixelate : simplifies the image with rectangles of the same color
  • Smooth : soften whole image, complementary to Sharpen
  • Sharpen : makes contours more accute, complementary to Smooth
  • Contour : draws contours on a white background (like a pencil drawing)
  • Emboss : draws contours with shadow
  • EmbossHighlight : draws contours of a selection defined with grayscale
  • Grayscale : converts colors to grayscale with gamma correction
  • Normalize : uses whole range of color luminosity
  • Rotate : rotation of the image around a point
  • Sphere : distorts the image to make it look like projected on a sphere
  • Twirl : distorts the image with a twirl effect
  • Cylinder : distorts the image to make it look like projected on a cylinder
  • Plane : computes a high precision projection on a horizontal plane. This is quite slow.
  • SmartZoom3 : resizes the image x3 and detects borders, to have a useful zoom with ancient games sprites

Some functions are not prefixed with Filter, because they do not return a newly allocated image. They modify the image in-place :

  • VerticalFlip : flips the image vertically
  • HorizontalFlip : flips the image horizontally
  • Negative : inverse of colors
  • LinearNegative : inverse without gamma correction
  • SwapRedBlue : swap red and blue channels (to convert between BGRA and RGBA)
  • ConvertToLinearRGB : to convert from sRGB to RGB. Note the format used by BGRABitmap is sRGB when using

dmDrawWithTransparency and RGB when using dmLinearBlend.

  • ConvertFromLinearRGB : convert from RGB to sRGB.

Images combination

PutImage is the basic image drawing function and BlendImage allows to combine images, like layers of image editing softwares. Available modes are the following:

  • LinearBlend : simple superimposition without gamma correction (equivalent to dmFastBlend)
  • Transparent : superimposition with gamma correction
  • Multiply : multiplication of color values (with gamma correction)
  • LinearMultiply : multiplication of color values (without gamma correction)
  • Additive : addition of color values (with gamma correction)
  • LinearAdd : addition of color values (without gamma correction)
  • Difference : difference of color values (with gamma correction)
  • LinearDifference : difference of color values (without gamma correction)
  • Negation : makes common colors disappear (with gamma correction)
  • LinearNegation : makes common colors disappear (without gamma correction)
  • Reflect, Glow : for light effects
  • ColorBurn, ColorDodge, Overlay, Screen : misc. filters
  • Lighten : keeps the lightest color values
  • Darken : keeps the darkest color values
  • Xor : exclusive or of color values

These modes can be used in TBGRALayeredBitmap, which makes it easier because BlendImage only provides the basic blending operations.

Screenshots

Lazpaint contour.png Lazpaint curve redim.png Bgra wirecube.png Bgra chessboard.jpg

Licence

modified LGPL

Author: Johann ELSASS (Facebook)

Download

Latest version: https://github.com/bgrabitmap/bgrabitmap/releases

Sourceforge with LazPaint: http://sourceforge.net/projects/lazpaint/files/src/

GitHub: https://github.com/bgrabitmap/

Old link : http://lazarus.johann-elsass.net/