/
bgrabitmaptypes.pas
1690 lines (1478 loc) 路 58.6 KB
/
bgrabitmaptypes.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: LGPL-3.0-linking-exception
{ @abstract(Basic types for BGRABitmap.)
This unit is generally needed in the **uses** clause,
along with the BGRABitmap unit.
It defines pixel types, image formats, text options, gemoetry types,
colors and base classes.
Whether you're using LCL types or not, add also BGRAGraphics unit rather
than Graphics unit to get the most portable types.
}
unit BGRABitmapTypes;
{$mode objfpc}{$H+}
{$i bgrabitmap.inc}
interface
uses
BGRAClasses, BGRAGraphics, BGRAUnicode,
FPImage{$IFDEF BGRABITMAP_USE_FPCANVAS}, FPImgCanv{$ENDIF}
{$IFDEF BGRABITMAP_USE_LCL}, LCLType, GraphType, LResources{$ENDIF}
{$IFNDEF BGRABITMAP_CORE}, BGRAMultiFileType{$ENDIF};
{=== Miscellaneous types ===}
{* Current version expressed as an integer with each part multiplied by 100 }
const BGRABitmapVersion = 11060200;
{* String representation of the version, numbers separated by dots }
function BGRABitmapVersionStr: string;
type
{$IFNDEF BGRABITMAP_CORE}TMultiFileContainer = BGRAMultiFileType.TMultiFileContainer;{$ENDIF}
Int32or64 = BGRAClasses.Int32or64;
UInt32or64 = BGRAClasses.UInt32or64;
{* Device context handle (using LCL if available) }
HDC = {$IFDEF BGRABITMAP_USE_LCL}LCLType.HDC{$ELSE}PtrUInt{$ENDIF};
type
{* Options when doing a floodfill (also called bucket fill) }
TFloodfillMode = (
{** Pixels that are filled are replaced }
fmSet,
{** Pixels that are filled are drawn upon with the fill color }
fmDrawWithTransparency,
{** Pixels that are filled are drawn without gamma correction upon with the fill color }
fmLinearBlend,
{** Pixels that are XORed with the fill color}
fmXor,
{** Pixels that are filled are drawn upon to the extent that the color underneath is similar to
the start color. The more different the different is, the less it is drawn upon }
fmProgressive);
{* Specifies how much smoothing is applied to the computation of the median }
TMedianOption = (moNone, moLowSmooth, moMediumSmooth, moHighSmooth);
{* Specifies the shape of a predefined blur }
TRadialBlurType = (
{** Gaussian-like, pixel importance decreases progressively }
rbNormal,
{** Disk blur, pixel importance does not decrease progressively }
rbDisk,
{** Pixel are considered when they are at a certain distance }
rbCorona,
{** Gaussian-like, but 10 times smaller than _rbNormal_ }
rbPrecise,
{** Gaussian-like but simplified to be computed faster }
rbFast,
{** Box blur, pixel importance does not decrease progressively
and the pixels are included when they are in a square.
This is much faster than _rbFast_ however you may get
square shapes in the resulting image }
rbBox);
{** String constants to represent TRadialBlurType values }
const RadialBlurTypeToStr: array[TRadialBlurType] of string =
('Normal','Disk','Corona','Precise','Fast','Box');
type
{* Possible options when applying emboss filter }
TEmbossOption = (
{** Transparent output except when there borders were detected }
eoTransparent,
{** Preserve the original hue }
eoPreserveHue);
{** Sets of emboss options }
TEmbossOptions = set of TEmbossOption;
{* List of image formats }
TBGRAImageFormat = (
{** Unknown format }
ifUnknown,
{** JPEG format, opaque, lossy compression }
ifJpeg,
{** PNG format, transparency, lossless compression. Can be animated (see BGRAAnimatedGif) }
ifPng,
{** GIF format, single transparent color, lossless in theory but only low number of colors allowed.
Can be animated (see BGRAAnimatedGif) }
ifGif,
{** BMP format, transparency, no compression. Note that transparency is
not supported by all BMP readers so it is recommended to avoid
storing images with transparency in this format }
ifBmp,
{** iGO BMP (16-bit, rudimentary lossless compression) }
ifBmpMioMap,
{** ICO format, contains different sizes of the same image }
ifIco,
{** CUR format, has hotspot, contains different sizes of the same image }
ifCur,
{** PCX format, opaque, rudimentary lossless compression }
ifPcx,
{** Paint.NET format, layers, lossless compression }
ifPaintDotNet,
{** LazPaint format, layers, lossless compression }
ifLazPaint,
{** OpenRaster format, layers, lossless compression }
ifOpenRaster,
{** Phoxo format, layers }
ifPhoxo,
{** Photoshop format, layers, rudimentary lossless compression }
ifPsd,
{** Targa format (TGA), transparency, rudimentary lossless compression }
ifTarga,
{** TIFF format, limited support }
ifTiff,
{** X-Window capture, limited support }
ifXwd,
{** X-Pixmap, text encoded image, limited support }
ifXPixMap,
{** text or binary encoded image, no compression, extension PBM, PGM, PPM }
ifPortableAnyMap,
{** Scalable Vector Graphic, vectorial, read-only as raster }
ifSvg,
{** Lossless or lossy compression using V8 algorithm (need libwebp library) }
ifWebP,
{** Lossless or lossy compression using Avif algorithm (need libavif library) }
ifAvif
);
var
{** List of stream readers for images }
DefaultBGRAImageReader: array[TBGRAImageFormat] of TFPCustomImageReaderClass;
{** List of stream writers for images }
DefaultBGRAImageWriter: array[TBGRAImageFormat] of TFPCustomImageWriterClass;
{** Detect the file format of a given file }
function DetectFileFormat(AFilenameUTF8: string): TBGRAImageFormat;
{** Detect the file format of a given stream. _ASuggestedExtensionUTF8_ can
be provided to guess the format }
function DetectFileFormat(AStream: TStream; ASuggestedExtensionUTF8: string = ''): TBGRAImageFormat;
{** Returns the file format that is most likely to be stored in the
given filename (according to its extension) }
function SuggestImageFormat(AFilenameOrExtensionUTF8: string): TBGRAImageFormat;
{** Returns a likely image extension for the format }
function SuggestImageExtension(AFormat: TBGRAImageFormat): string;
{** Create an image reader for the given format }
function CreateBGRAImageReader(AFormat: TBGRAImageFormat): TFPCustomImageReader;
{** Create an image writer for the given format. _AHasTransparentPixels_
specifies if alpha channel must be supported }
function CreateBGRAImageWriter(AFormat: TBGRAImageFormat; AHasTransparentPixels: boolean): TFPCustomImageWriter;
type
{* Possible options when loading an image }
TBGRALoadingOption = (
{** Do not clear RGB channels when alpha is zero (not recommended) }
loKeepTransparentRGB,
{** Consider BMP to be opaque if no alpha value is provided (for compatibility) }
loBmpAutoOpaque,
{** Load JPEG quickly however with a lower quality }
loJpegQuick);
{** Set of options when loading }
TBGRALoadingOptions = set of TBGRALoadingOption;
TTextLayout = BGRAGraphics.TTextLayout;
const
tlTop = BGRAGraphics.tlTop;
tlCenter = BGRAGraphics.tlCenter;
tlBottom = BGRAGraphics.tlBottom;
type
TFontBidiMode = BGRAUnicode.TFontBidiMode;
const
fbmAuto = BGRAUnicode.fbmAuto;
fbmLeftToRight = BGRAUnicode.fbmLeftToRight;
fbmRightToLeft = BGRAUnicode.fbmRightToLeft;
type
{* Alignment relative to the bidi-mode }
TBidiTextAlignment = (
{** Natural alignment: left-aligned for left-to-right and right-aligned for right-to-left text }
btaNatural,
{** Opposite of natural alignment }
btaOpposite,
{** Always left-aligned }
btaLeftJustify,
{** Always right-aligned }
btaRightJustify,
{** Centered }
btaCenter);
{** Converts an alignment to a bidi alignement relative to a bidi-mode }
function AlignmentToBidiTextAlignment(AAlign: TAlignment; ARightToLeft: boolean): TBidiTextAlignment; overload;
{** Converts an alignment to a bidi alignement independent of bidi-mode }
function AlignmentToBidiTextAlignment(AAlign: TAlignment): TBidiTextAlignment; overload;
{** Converts a bidi alignment to a classic alignement according to bidi-mode }
function BidiTextAlignmentToAlignment(ABidiAlign: TBidiTextAlignment; ARightToLeft: boolean): TAlignment;
{* Checks the bounds of an image in the given clipping rectangle }
function CheckPutImageBounds(x, y, tx, ty: integer; out minxb, minyb, maxxb, maxyb, ignoreleft: integer; const cliprect: TRect): boolean;
{==== Imported from GraphType ====}
//if this unit is defined, otherwise
//define here the types used by the library.
{$IFDEF BGRABITMAP_USE_LCL}
type
{ Order of the lines in an image }
TRawImageLineOrder = GraphType.TRawImageLineOrder;
{ Order of the bits in a byte containing pixel values }
TRawImageBitOrder = GraphType.TRawImageBitOrder;
{ Order of the bytes in a group of byte containing pixel values }
TRawImageByteOrder = GraphType.TRawImageByteOrder;
{ Definition of a single line 3D bevel }
TGraphicsBevelCut = GraphType.TGraphicsBevelCut;
const
{ The first line (line 0) is the top line }
riloTopToBottom = GraphType.riloTopToBottom;
{ The first line (line 0) is the bottom line }
riloBottomToTop = GraphType.riloBottomToTop;
{ Bit 0 is pixel 0 }
riboBitsInOrder = GraphType.riboBitsInOrder;
{ Bit 0 is pixel 7 (Bit 1 is pixel 6, ...) }
riboReversedBits = GraphType.riboReversedBits;
{ least significant byte first (little endian) }
riboLSBFirst = GraphType.riboLSBFirst;
{ most significant byte first (big endian) }
riboMSBFirst = GraphType.riboMSBFirst;
{ fill till the color (it fills all except this color) }
fsSurface = GraphType.fsSurface;
{ fill this color (it fills only connected pixels of this color)聽}
fsBorder = GraphType.fsBorder;
{ No bevel }
bvNone = GraphType.bvNone;
{ Bevel for lowered surface }
bvLowered = GraphType.bvLowered;
{ Bevel for raised surface }
bvRaised = GraphType.bvRaised;
{ Spacing only }
bvSpace = GraphType.bvSpace;
{$ELSE}
type
{* Order of the lines in an image }
TRawImageLineOrder = (
{** The first line in memory (line 0) is the top line }
riloTopToBottom,
{** The first line in memory (line 0) is the bottom line }
riloBottomToTop);
{* Order of the bits in a byte containing pixel values }
TRawImageBitOrder = (
{** The lowest bit is on the left. So with a monochrome picture, bit 0 would be pixel 0 }
riboBitsInOrder,
{** The lowest bit is on the right. So with a momochrome picture, bit 0 would be pixel 7 (bit 1 would be pixel 6, ...) }
riboReversedBits);
{* Order of the bytes in a group of byte containing pixel values }
TRawImageByteOrder = (
{** Least significant byte first (little endian) }
riboLSBFirst,
{** most significant byte first (big endian) }
riboMSBFirst);
{* Definition of a single line 3D bevel }
TGraphicsBevelCut =
(
{** No bevel }
bvNone,
{** Shape is lowered, light is on the bottom-right corner }
bvLowered,
{** Shape is raised, light is on the top-left corner }
bvRaised,
{** Shape is at the same level, there is no particular lighting }
bvSpace);
{$ENDIF}
{$DEFINE INCLUDE_INTERFACE}
{$I bgrapixel.inc}
{$DEFINE INCLUDE_INTERFACE}
{$I geometrytypes.inc}
{$DEFINE INCLUDE_INTERFACE}
{$i csscolorconst.inc}
{$DEFINE INCLUDE_INTERFACE}
{$I bgrascanner.inc}
{$DEFINE INCLUDE_INTERFACE}
{$I unibitmap.inc}
{$DEFINE INCLUDE_INTERFACE}
{$I unibitmapgeneric.inc}
{==== Integer math ====}
{* Computes the value modulo cycle, and if the _value_ is negative, the result
is still positive }
function PositiveMod(value, cycle: Int32or64): Int32or64; inline; overload;
{ Sin65536 and Cos65536 are fast routines to compute sine and cosine as integer values.
They use a table to store already computed values. The return value is an integer
ranging from 0 to 65536, so the mean value is 32768 and the half amplitude is
32768 instead of 1. The input has a period of 65536, so you can supply any integer
without applying a modulo. }
{ * Compute all sin values now }
procedure PrecalcSin65536;
{* Returns an integer approximation of the sine. Value ranges from 0 to 65535,
where 65536 corresponds to the next cycle }
function Sin65536(value: word): Int32or64; inline;
{* Returns an integer approximation of the cosine. Value ranges from 0 to 65535,
where 65536 corresponds to the next cycle }
function Cos65536(value: word): Int32or64; inline;
{* Returns the square root of the given byte, considering that
255 is equal to unity }
function ByteSqrt(value: byte): byte; inline;
{* Rounds the number to the nearest integer. If the number is exactly halfway
between two integers, it rounds towards positive infinity. }
function HalfUp(value: single): integer;
{* Rounds the number to the nearest 64-bit integer. If the number is exactly halfway
between two integers, it rounds towards positive infinity. }
function HalfUp64(value: single): Int64;
{==== Types provided for fonts ====}
type
{* Quality to be used to render text }
TBGRAFontQuality = (
{** Use the system capabilities. It is rather fast however it may be
not be smoothed. }
fqSystem,
{** Use the system capabilities to render with ClearType. This quality is
of course better than _fqSystem_ however it may not be perfect.}
fqSystemClearType,
{** Garanties a high quality antialiasing. }
fqFineAntialiasing,
{** Fine antialiasing with ClearType assuming an LCD display in red/green/blue order }
fqFineClearTypeRGB,
{** Fine antialiasing with ClearType assuming an LCD display in blue/green/red order }
fqFineClearTypeBGR);
{** Function type to detect the adequate ClearType mode }
TGetFineClearTypeAutoFunc = function(): TBGRAFontQuality;
var
{** Provide function to detect the adequate ClearType mode }
fqFineClearType : TGetFineClearTypeAutoFunc;
type
{* Measurements of a font }
TFontPixelMetric = record
{** The values have been computed }
Defined: boolean;
{** Position of the baseline, where most letters lie }
Baseline,
{** Position of the top of the small letters (x being one of them) }
xLine,
{** Position of the top of the UPPERCASE letters }
CapLine,
{** Position of the bottom of letters like g and p }
DescentLine,
{** Total line height including line spacing defined by the font }
Lineheight: integer;
end;
{* Measurements of a font in floating point values }
TFontPixelMetricF = record
{** The values have been computed }
Defined: boolean;
{** Position of the baseline, where most letters lie }
Baseline,
{** Position of the top of the small letters (x being one of them) }
xLine,
{** Position of the top of the UPPERCASE letters }
CapLine,
{** Position of the bottom of letters like g and p }
DescentLine,
{** Total line height including line spacing defined by the font }
Lineheight: single;
end;
{* Vertical anchoring of the font. When text is drawn, a start coordinate
is necessary. Text can be positioned in different ways. This enum
defines what position it is regarding the font }
TFontVerticalAnchor = (
{** The top of the font. Everything will be drawn below the start coordinate. }
fvaTop,
{** The center of the font }
fvaCenter,
{** The top of capital letters }
fvaCapLine,
{** The center of capital letters }
fvaCapCenter,
{** The top of small letters }
fvaXLine,
{** The center of small letters }
fvaXCenter,
{** The baseline, the bottom of most letters }
fvaBaseline,
{** The bottom of letters that go below the baseline }
fvaDescentLine,
{** The bottom of the font. Everything will be drawn above the start coordinate }
fvaBottom);
{* Definition of a function that handles work-break }
TWordBreakHandler = procedure(var ABeforeUTF8, AAfterUTF8: string) of object;
{* Alignment for a typewriter, that does not have any more information
than a square shape containing glyphs }
TBGRATypeWriterAlignment = (twaTopLeft, twaTop, twaTopRight, twaLeft, twaMiddle, twaRight, twaBottomLeft, twaBottom, twaBottomRight);
{* How a typewriter must render its content on a Canvas2d }
TBGRATypeWriterOutlineMode = (twoPath, twoFill, twoStroke, twoFillOverStroke, twoStrokeOverFill, twoFillThenStroke, twoStrokeThenFill);
{* Abstract class for all font renderers }
TBGRACustomFontRenderer = class
protected
{** Specifies the height of the font without taking into account additional line spacing.
A negative value means that it is the full height instead }
FFontEmHeightF: single;
{** Retrieves the em-height of the font }
function GetFontEmHeight: integer;
{** Sets the font height as em-height }
procedure SetFontEmHeight(AValue: integer);
public
{** Specifies the font to use. Unless the font renderer accept otherwise,
the name is in human readable form, like 'Arial', 'Times New Roman', ... }
FontName: string;
{** Specifies the set of styles to be applied to the font.
These can be fsBold, fsItalic, fsStrikeOut, fsUnderline.
So the value \[fsBold, fsItalic] means that the font must be bold and italic }
FontStyle: TFontStyles;
{** Specifies the quality of rendering. Default value is fqSystem }
FontQuality: TBGRAFontQuality;
{** Specifies the rotation of the text, for functions that support text rotation.
It is expressed in tenth of degrees, positive values going counter-clockwise }
FontOrientation: integer;
{** Returns measurement for the current font in pixels }
function GetFontPixelMetric: TFontPixelMetric; virtual; abstract;
{** Returns measurement for the current font in fractional pixels }
function GetFontPixelMetricF: TFontPixelMetricF; virtual;
{** Checks whether a font exists }
function FontExists(AName: string): boolean; virtual; abstract;
{** Checks if any text would be visible using the specified color }
function TextVisible(const AColor: TBGRAPixel): boolean; virtual;
{** Returns the total size of the string provided using the current font.
Orientation is not taken into account, so that the width is horizontal }
function TextSize(sUTF8: string): TSize; overload; virtual; abstract;
{** Returns the total floating point size of the string provided using the current font.
Orientation is not taken into account, so that the width is horizontal }
function TextSizeF(sUTF8: string): TPointF; overload; virtual;
{** Returns the total size of the string provided given a maximum width and RTL mode,
using the current font. Orientation is not taken into account,
so that the width is along the text }
function TextSize(sUTF8: string; AMaxWidth: integer; ARightToLeft: boolean): TSize; overload; virtual; abstract;
{** Returns the total floating point size of the string provided given a maximum width and RTL mode,
using the current font. Orientation is not taken into account,
so that the width is along the text }
function TextSizeF(sUTF8: string; AMaxWidthF: single; ARightToLeft: boolean): TPointF; overload; virtual;
{** Returns the total size of the string provided using the current font,
with the given orientation in tenth of degrees CCW, along the text }
function TextSizeAngle(sUTF8: string; {%H-}orientationTenthDegCCW: integer): TSize; virtual;
{** Returns the total floating-point size of the string provided using the current font,
with the given orientation, along the text }
function TextSizeAngleF(sUTF8: string; {%H-}orientationTenthDegCCW: integer): TPointF; virtual;
{** Returns the number of Unicode characters that fit into the specified size }
function TextFitInfo(sUTF8: string; AMaxWidth: integer): integer; virtual; abstract;
{** Returns the number of Unicode characters that fit into the specified floating-point size }
function TextFitInfoF(sUTF8: string; AMaxWidthF: single): integer; virtual;
{** Draws the UTF8 encoded string, with color _c_.
If align is taLeftJustify, (_x_, _y_) is the top-left corner.
If align is taCenter, (_x_, _y_) is at the top and middle of the text.
If align is taRightJustify, (_x_, _y_) is the top-right corner.
The value of _FontOrientation_ is taken into account, so that the text may be rotated }
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; c: TBGRAPixel; align: TAlignment); overload; virtual; abstract;
{** Same as above but with given RTL mode }
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; c: TBGRAPixel; align: TAlignment; {%H-}ARightToLeft: boolean); overload; virtual;
{** Same as above functions, except that the text is filled using texture.
The value of _FontOrientation_ is taken into account, so that the text may be rotated }
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; texture: IBGRAScanner; align: TAlignment); overload; virtual; abstract;
{** Same as above but with given RTL mode }
procedure TextOut(ADest: TBGRACustomBitmap; x, y: single; sUTF8: string; texture: IBGRAScanner; align: TAlignment; {%H-}ARightToLeft: boolean); overload; virtual;
{** Same as above, except that the orientation is specified in tenth of degrees CCW,
overriding the value of the property _FontOrientation_ }
procedure TextOutAngle(ADest: TBGRACustomBitmap; x, y: single; orientationTenthDegCCW: integer; sUTF8: string; c: TBGRAPixel; align: TAlignment); overload; virtual; abstract;
{** Same as above but with given RTL mode }
procedure TextOutAngle(ADest: TBGRACustomBitmap; x, y: single; orientationTenthDegCCW: integer; sUTF8: string; c: TBGRAPixel; align: TAlignment; {%H-}ARightToLeft: boolean); overload; virtual;
{** Same as above, except that the orientation is specified, overriding the value of the property _FontOrientation_ }
procedure TextOutAngle(ADest: TBGRACustomBitmap; x, y: single; orientationTenthDegCCW: integer; sUTF8: string; texture: IBGRAScanner; align: TAlignment); overload; virtual; abstract;
{** Same as above but with given RTL mode }
procedure TextOutAngle(ADest: TBGRACustomBitmap; x, y: single; orientationTenthDegCCW: integer; sUTF8: string; texture: IBGRAScanner; align: TAlignment; {%H-}ARightToLeft: boolean); overload; virtual;
{** Draw the UTF8 encoded string at the coordinate (_x_, _y_), clipped inside the rectangle _ARect_.
Additional style information is provided by the style parameter.
The color _c_ is used to fill the text. No rotation is applied. }
procedure TextRect(ADest: TBGRACustomBitmap; ARect: TRect; x, y: integer; sUTF8: string; style: TTextStyle; c: TBGRAPixel); overload; virtual; abstract;
{** Same as above except a _texture_ is used to fill the text }
procedure TextRect(ADest: TBGRACustomBitmap; ARect: TRect; x, y: integer; sUTF8: string; style: TTextStyle; texture: IBGRAScanner); overload; virtual; abstract;
{** Copy the path for the UTF8 encoded string into _ADest_.
If _align_ is _taLeftJustify_, (_x_, _y_) is the top-left corner.
If _align_ is _taCenter_, (_x_, _y_) is at the top and middle of the text.
If _align_ is _taRightJustify_, (_x_, _y_) is the top-right corner. }
procedure CopyTextPathTo({%H-}ADest: IBGRAPath; {%H-}x, {%H-}y: single; {%H-}s: string; {%H-}align: TAlignment); virtual; //optional
{** Same as above but with given RTL mode }
procedure CopyTextPathTo({%H-}ADest: IBGRAPath; {%H-}x, {%H-}y: single; {%H-}s: string; {%H-}align: TAlignment; {%H-}ARightToLeft: boolean); virtual; //optional
{** Check whether the renderer can produce text path }
function HandlesTextPath: boolean; virtual;
{** Font em-height as an integer }
property FontEmHeight: integer read GetFontEmHeight write SetFontEmHeight;
{** Font em-height as a single-precision floating point value }
property FontEmHeightF: single read FFontEmHeightF write FFontEmHeightF;
end;
{* Output mode for the improved renderer for readability.
This is used by the font renderer based on LCL in BGRAText }
TBGRATextOutImproveReadabilityMode = (
{** Render the grayscale mask }
irMask,
{** Render normally with provided the color or texture }
irNormal,
{** Render with ClearType for RGB ordered display }
irClearTypeRGB,
{** Render with ClearType for BGR ordered display }
irClearTypeBGR);
{* Removes line ending and tab characters from a string (for a function
like _TextOut_ that does not handle this). this works with UTF8 strings
as well }
function CleanTextOutString(const s: string): string;
{* Remove the line ending at the specified position or return False.
This works with UTF8 strings however the index is the byte index }
function RemoveLineEnding(var s: string; indexByte: integer): boolean;
{* Remove the line ending at the specified position or return False.
The index is the character index, that may be different from the
byte index }
function RemoveLineEndingUTF8(var sUTF8: string; indexUTF8: integer): boolean;
{* Default word break handler }
procedure BGRADefaultWordBreakHandler(var ABefore, AAfter: string);
{==== Images and resampling ====}
type
{* How the resample is to be computed }
TResampleMode = (
{** Low quality resample by repeating pixels, stretching them }
rmSimpleStretch,
{** Use resample filters. This gives high
quality resampling however this the proportion changes slightly because
the first and last pixel are considered to occupy only half a unit as
they are considered as the border of the picture
(pixel-centered coordinates) }
rmFineResample);
{* List of resample filter to be used with _rmFineResample_ }
TResampleFilter = (
{** Equivalent of simple stretch with high quality and pixel-centered coordinates }
rfBox,
{** Linear interpolation giving slow transition between pixels }
rfLinear,
{** Mix of _rfLinear_ and _rfCosine_ giving medium speed stransition between pixels }
rfHalfCosine,
{** Cosine-like interpolation giving fast transition between pixels }
rfCosine,
{** Simple bi-cubic filter (blurry) }
rfBicubic,
{** Mitchell filter, good for downsizing interpolation }
rfMitchell,
{** Spline filter, good for upsizing interpolation, however slightly blurry }
rfSpline,
{** Lanczos with radius 2, blur is corrected }
rfLanczos2,
{** Lanczos with radius 3, high contrast }
rfLanczos3,
{** Lanczos with radius 4, high contrast }
rfLanczos4,
{** Best quality using rfMitchell or rfSpline }
rfBestQuality);
const
{** List of strings to represent resample filters }
ResampleFilterStr : array[TResampleFilter] of string =
('Box','Linear','HalfCosine','Cosine','Bicubic','Mitchell','Spline',
'Lanczos2','Lanczos3','Lanczos4','BestQuality');
{** Gives the sample filter represented by a string }
function StrToResampleFilter(str: string): TResampleFilter;
type
{* Image information from superficial analysis }
TQuickImageInfo = record
{** Width in pixels }
Width,
{** Height in pixels }
Height,
{** Bitdepth for colors (1, 2, 4, 8 for images with palette/grayscale, 16, 24 or 48 if each channel is present) }
ColorDepth,
{** Bitdepth for alpha (0 if no alpha channel, 1 if bit mask, 8 or 16 if alpha channel) }
AlphaDepth: integer;
end;
{* Bitmap reader with additional features }
TBGRAImageReader = class(TFPCustomImageReader)
{** Return bitmap information (size, bit depth) }
function GetQuickInfo(AStream: TStream): TQuickImageInfo; virtual; abstract;
{** Return a draft of the bitmap, the ratio may change compared to the original width and height (useful to make thumbnails) }
function GetBitmapDraft(AStream: TStream; AMaxWidth, AMaxHeight: integer; out AOriginalWidth,AOriginalHeight: integer): TBGRACustomBitmap; virtual; abstract;
end;
{* Generic definition for a PNG writer with alpha option }
TBGRACustomWriterPNG = class(TFPCustomImageWriter)
protected
{** Gets whether or not to use the alpha channel }
function GetUseAlpha: boolean; virtual; abstract;
{** Sets whether or not to use the alpha channel }
procedure SetUseAlpha(AValue: boolean); virtual; abstract;
public
{** Whether or not to use the alpha channel }
property UseAlpha : boolean read GetUseAlpha write SetUseAlpha;
end;
{$DEFINE INCLUDE_INTERFACE}
{$I bgracustombitmap.inc}
{* Check whether to GUID are equal }
operator =(const AGuid1, AGuid2: TGuid): boolean;
type
{* Generic class for embedded resource management }
TBGRAResourceManager = class
protected
function GetWinResourceType(AExtension: string): pchar;
public
function GetResourceStream(AFilename: string): TStream; virtual;
function IsWinResource(AFilename: string): boolean; virtual;
end;
{** Provides a resource manager聽}
var BGRAResource : TBGRAResourceManager;
{* Return the full path for a resource file on the disk. On Windows and Linux, it
can be next to the binary but on MacOS, it can be outside of the application bundle
when debugging }
function ResourceFile(AFilename: string): string;
implementation
uses Math, SysUtils, BGRAUTF8, FPWriteBMP, FPReadPNM, FPWritePNM, FPWriteXPM{$IFNDEF BGRABITMAP_CORE},
FPReadXwd, FPReadXPM, FPReadPcx,
FPWriteJPEG, FPWritePCX,
FPWriteTGA{$ENDIF};
function BGRABitmapVersionStr: string;
var numbers: TStringList;
i,remaining: LongWord;
begin
numbers := TStringList.Create;
remaining := BGRABitmapVersion;
for i := 1 to 4 do
begin
numbers.Insert(0, IntToStr(remaining mod 100));
remaining := remaining div 100;
end;
while (numbers.Count > 1) and (numbers[numbers.Count-1]='0') do
numbers.Delete(numbers.Count-1);
numbers.Delimiter:= '.';
result := numbers.DelimitedText;
numbers.Free;
end;
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I geometrytypes.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I unibitmap.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I unibitmapgeneric.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I csscolorconst.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I bgracustombitmap.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I bgrascanner.inc}
{$DEFINE INCLUDE_IMPLEMENTATION}
{$I bgrapixel.inc}
function AlignmentToBidiTextAlignment(AAlign: TAlignment; ARightToLeft: boolean): TBidiTextAlignment;
begin
case AAlign of
taCenter: result := btaCenter;
taRightJustify: if ARightToLeft then result := btaNatural else result := btaOpposite;
else {taLeftJustify}
if ARightToLeft then result := btaOpposite else result := btaNatural;
end;
end;
function AlignmentToBidiTextAlignment(AAlign: TAlignment): TBidiTextAlignment;
begin
case AAlign of
taCenter: result := btaCenter;
taRightJustify: result := btaRightJustify;
else {taLeftJustify}
result := btaLeftJustify;
end;
end;
function BidiTextAlignmentToAlignment(ABidiAlign: TBidiTextAlignment;
ARightToLeft: boolean): TAlignment;
begin
case ABidiAlign of
btaCenter: result := taCenter;
btaLeftJustify: result := taLeftJustify;
btaRightJustify: result := taRightJustify;
btaOpposite: if ARightToLeft then result := taLeftJustify else result := taRightJustify;
else {btaNatural}
if ARightToLeft then result := taRightJustify else result := taLeftJustify;
end;
end;
function CleanTextOutString(const s: string): string;
var idxIn, idxOut: integer;
begin
setlength(result, length(s));
idxIn := 1;
idxOut := 1;
while IdxIn <= length(s) do
begin
if not (s[idxIn] in[#13,#10,#9]) then //those characters are always 1 byte long so it is the same with UTF8
begin
result[idxOut] := s[idxIn];
inc(idxOut);
end;
inc(idxIn);
end;
setlength(result, idxOut-1);
end;
function RemoveLineEnding(var s: string; indexByte: integer): boolean;
begin //we can ignore UTF8 character length because #13 and #10 are always 1 byte long
//so this function can be applied to UTF8 strings as well
result := false;
if length(s) >= indexByte then
begin
if s[indexByte] in[#13,#10] then
begin
result := true;
if length(s) >= indexByte+1 then
begin
if (s[indexByte+1] <> s[indexByte]) and (s[indexByte+1] in[#13,#10]) then
delete(s,indexByte,2)
else
delete(s,indexByte,1);
end
else
delete(s,indexByte,1);
end else
if (s[indexByte] = #$C2) and (length(s) >= indexByte+1) and (s[indexByte+1] = #$85) then
begin
result := true;
delete(s,indexByte,2);
end else
if (s[indexByte] = #$E2) and (length(s) >= indexByte+2) and (s[indexByte+1] = #$80) and
(s[indexByte+2] in[#$A8,#$A9]) then
begin
result := true;
delete(s,indexByte,3);
end
end;
end;
function RemoveLineEndingUTF8(var sUTF8: string; indexUTF8: integer): boolean;
var indexByte: integer;
pIndex: PChar;
begin
pIndex := UTF8CharStart(@sUTF8[1],length(sUTF8),indexUTF8);
if pIndex = nil then
begin
result := false;
exit;
end;
indexByte := pIndex - @sUTF8[1];
result := RemoveLineEnding(sUTF8, indexByte);
end;
procedure BGRADefaultWordBreakHandler(var ABefore, AAfter: string);
const spacingChars = [' '];
wordBreakChars = [' ',#9,'-','?','!'];
var p, charLen: integer;
u: LongWord;
begin
if (AAfter <> '') and (ABefore <> '') and not (AAfter[1] in spacingChars) and not (ABefore[length(ABefore)] in wordBreakChars) then
begin
p := length(ABefore);
while (p > 1) and not (ABefore[p-1] in wordBreakChars) do dec(p);
while (p < length(ABefore)+1) and (ABefore[p] in [#$80..#$BF]) do inc(p); //do not split UTF8 char
//keep non-spacing mark together
while p <= length(ABefore) do
begin
charLen := UTF8CharacterLength(@ABefore[p]);
if p+charLen > length(ABefore)+1 then charLen := length(ABefore)+1-p;
u := UTF8CodepointToUnicode(@ABefore[p],charLen);
if (GetUnicodeBidiClassEx(u) in[ubcNonSpacingMark, ubcCombiningLeftToRight]) then
inc(p,charLen)
else
break;
end;
if p = 1 then
begin
//keep ideographic punctuation together
charLen := UTF8CharacterLength(@AAfter[p]);
if charLen > length(AAfter) then charLen := length(AAfter);
u := UTF8CodepointToUnicode(@AAfter[p],charLen);
case u of
UNICODE_IDEOGRAPHIC_COMMA,
UNICODE_IDEOGRAPHIC_FULL_STOP,
UNICODE_FULLWIDTH_COMMA,
UNICODE_HORIZONTAL_ELLIPSIS:
begin
p := length(ABefore)+1;
while p > 1 do
begin
charLen := 1;
dec(p);
while (p > 0) and (ABefore[p] in [#$80..#$BF]) do
begin
dec(p); //do not split UTF8 char
inc(charLen);
end;
if charLen <= 4 then
u := UTF8CodepointToUnicode(@ABefore[p],charLen)
else
u := ord('A');
case GetUnicodeBidiClass(u) of
ubcNonSpacingMark: ; // include NSM
ubcOtherNeutrals, ubcWhiteSpace, ubcCommonSeparator, ubcEuropeanNumberSeparator:
begin
p := 1;
break;
end
else
break;
end;
end;
end;
end;
end;
if p > 1 then //can put the word after
begin
AAfter := copy(ABefore,p,length(ABefore)-p+1)+AAfter;
ABefore := copy(ABefore,1,p-1);
end else
begin //cannot put the word after, so before
end;
end;
while (ABefore <> '') and (ABefore[length(ABefore)] in spacingChars) do delete(ABefore,length(ABefore),1);
while (AAfter <> '') and (AAfter[1] in spacingChars) do delete(AAfter,1,1);
end;
function StrToResampleFilter(str: string): TResampleFilter;
var f: TResampleFilter;
begin
result := rfLinear;
str := LowerCase(str);
for f := low(TResampleFilter) to high(TResampleFilter) do
if CompareText(str,ResampleFilterStr[f])=0 then
begin
result := f;
exit;
end;
end;
function GetFineClearTypeAuto: TBGRAFontQuality;
begin
result := fqFineClearTypeRGB;
end;
{ TBGRACustomFontRenderer }
function TBGRACustomFontRenderer.GetFontEmHeight: integer;
begin
result := round(FFontEmHeightF);
end;
procedure TBGRACustomFontRenderer.SetFontEmHeight(AValue: integer);
begin
FFontEmHeightF:= AValue;
end;
function TBGRACustomFontRenderer.GetFontPixelMetricF: TFontPixelMetricF;
begin
with GetFontPixelMetric do
begin
result.Defined := Defined;
result.Baseline := Baseline;
result.xLine := xLine;
result.CapLine := CapLine;
result.DescentLine := DescentLine;
result.Lineheight := LineHeight;
end;
end;
function TBGRACustomFontRenderer.TextVisible(const AColor: TBGRAPixel): boolean;
begin
result := AColor.alpha <> 0;
end;
function TBGRACustomFontRenderer.TextSizeF(sUTF8: string): TPointF;
begin
with TextSize(sUTF8) do
result := PointF(cx,cy);
end;
function TBGRACustomFontRenderer.TextSizeF(sUTF8: string; AMaxWidthF: single;
ARightToLeft: boolean): TPointF;
begin
with TextSize(sUTF8, round(AMaxWidthF), ARightToLeft) do
result := PointF(cx,cy);
end;
function TBGRACustomFontRenderer.TextFitInfoF(sUTF8: string; AMaxWidthF: single): integer;
begin
result := TextFitInfo(sUTF8, round(AMaxWidthF));
end;
function TBGRACustomFontRenderer.TextSizeAngle(sUTF8: string;
orientationTenthDegCCW: integer): TSize;
begin
result := TextSize(sUTF8); //ignore orientation by default
end;
function TBGRACustomFontRenderer.TextSizeAngleF(sUTF8: string;
orientationTenthDegCCW: integer): TPointF;
begin
result := TextSizeF(sUTF8); //ignore orientation by default
end;
procedure TBGRACustomFontRenderer.TextOut(ADest: TBGRACustomBitmap; x,
y: single; sUTF8: string; c: TBGRAPixel; align: TAlignment;
ARightToLeft: boolean);
begin
//if RightToLeft is not handled
TextOut(ADest,x,y,sUTF8,c,align);
end;
procedure TBGRACustomFontRenderer.TextOut(ADest: TBGRACustomBitmap; x,
y: single; sUTF8: string; texture: IBGRAScanner; align: TAlignment;
ARightToLeft: boolean);
begin
//if RightToLeft is not handled
TextOut(ADest,x,y,sUTF8,texture,align);
end;
procedure TBGRACustomFontRenderer.TextOutAngle(ADest: TBGRACustomBitmap; x,
y: single; orientationTenthDegCCW: integer; sUTF8: string; c: TBGRAPixel;
align: TAlignment; ARightToLeft: boolean);
begin
//if RightToLeft is not handled
TextOutAngle(ADest,x,y,orientationTenthDegCCW,sUTF8,c,align);
end;