blob: c9ceaab83a1e658e21f78345470c1642d779f49b [file] [log] [blame]
#Topic Canvas
#Alias Canvas_Reference ##
#Class SkCanvas
Canvas provides an interface for drawing, and how the drawing is clipped and transformed.
Canvas contains a stack of Matrix and Clip values.
Canvas and Paint together provide the state to draw into Surface or Device.
Each Canvas draw call transforms the geometry of the object by the concatenation of all
Matrix values in the stack. The transformed geometry is clipped by the intersection
of all of Clip values in the stack. The Canvas draw calls use Paint to supply drawing
state such as Color, Typeface, text size, stroke width, Shader and so on.
To draw to a pixel-based destination, create Raster_Surface or GPU_Surface.
Request Canvas from Surface to obtain the interface to draw.
Canvas generated by Raster_Surface draws to memory visible to the CPU.
Canvas generated by GPU_Surface uses Vulkan or OpenGL to draw to the GPU.
To draw to a document, obtain Canvas from SVG_Canvas, Document_PDF, or Picture_Recorder.
Document based Canvas and other Canvas Subclasses reference Device describing the
destination.
Canvas can be constructed to draw to Bitmap without first creating Raster_Surface.
This approach may be deprecated in the future.
#Subtopic Overview
#Populate
##
#Subtopic Related_Function
#Populate
##
#Subtopic Constant
#Populate
##
#Subtopic Struct
#Populate
##
#Subtopic Typedef
#Populate
##
#Subtopic Constructor
Create the desired type of Surface to obtain its Canvas when possible. Useful
when no Surface is required, and some helpers implicitly create Raster_Surface.
#Populate
##
#Subtopic Member_Function
#Populate
##
# ------------------------------------------------------------------------------
#Method static std::unique_ptr<SkCanvas> MakeRasterDirect(const SkImageInfo& info, void* pixels,
size_t rowBytes,
const SkSurfaceProps* props = nullptr)
#In Constructor
#Line # creates from SkImageInfo and Pixel_Storage ##
Allocates raster Canvas that will draw directly into pixels.
Canvas is returned if all parameters are valid.
Valid parameters include:
info dimensions are zero or positive;
info contains Color_Type and Alpha_Type supported by Raster_Surface;
pixels is not nullptr;
rowBytes is zero or large enough to contain info width pixels of Color_Type.
Pass zero for rowBytes to compute rowBytes from info width and size of pixel.
If rowBytes is greater than zero, it must be equal to or greater than
info width times bytes required for Color_Type.
Pixel buffer size should be info height times computed rowBytes.
Pixels are not initialized.
To access pixels after drawing, call flush() or peekPixels.
#Param info width, height, Color_Type, Alpha_Type, Color_Space, of Raster_Surface;
width, or height, or both, may be zero
##
#Param pixels pointer to destination pixels buffer
##
#Param rowBytes interval from one Surface row to the next, or zero
##
#Param props LCD striping orientation and setting for device independent fonts;
may be nullptr
##
#Return Canvas if all parameters are valid; otherwise, nullptr ##
#Example
#Description
Allocates a three by three bitmap, clears it to white, and draws a black pixel
in the center.
##
void draw(SkCanvas* ) {
SkImageInfo info = SkImageInfo::MakeN32Premul(3, 3); // device aligned, 32 bpp, Premultiplied
const size_t minRowBytes = info.minRowBytes(); // bytes used by one bitmap row
const size_t size = info.computeMinByteSize(); // bytes used by all rows
SkAutoTMalloc<SkPMColor> storage(size); // allocate storage for pixels
SkPMColor* pixels = storage.get(); // get pointer to allocated storage
// create a SkCanvas backed by a raster device, and delete it when the
// function goes out of scope.
std::unique_ptr<SkCanvas> canvas = SkCanvas::MakeRasterDirect(info, pixels, minRowBytes);
canvas->clear(SK_ColorWHITE); // white is Unpremultiplied, in ARGB order
canvas->flush(); // ensure that pixels are cleared
SkPMColor pmWhite = pixels[0]; // the Premultiplied format may vary
SkPaint paint; // by default, draws black
canvas->drawPoint(1, 1, paint); // draw in the center
canvas->flush(); // ensure that point was drawn
for (int y = 0; y < info.height(); ++y) {
for (int x = 0; x < info.width(); ++x) {
SkDebugf("%c", *pixels++ == pmWhite ? '-' : 'x');
}
SkDebugf("\n");
}
}
#StdOut
---
-x-
---
##
##
#SeeAlso MakeRasterDirectN32 SkSurface::MakeRasterDirect
##
# ------------------------------------------------------------------------------
#Method static std::unique_ptr<SkCanvas> MakeRasterDirectN32(int width, int height, SkPMColor* pixels,
size_t rowBytes)
#In Constructor
#Line # creates from image data and Pixel_Storage ##
Allocates raster Canvas specified by inline image specification. Subsequent Canvas
calls draw into pixels.
Color_Type is set to kN32_SkColorType.
Alpha_Type is set to kPremul_SkAlphaType.
To access pixels after drawing, call flush() or peekPixels.
Canvas is returned if all parameters are valid.
Valid parameters include:
width and height are zero or positive;
pixels is not nullptr;
rowBytes is zero or large enough to contain width pixels of kN32_SkColorType.
Pass zero for rowBytes to compute rowBytes from width and size of pixel.
If rowBytes is greater than zero, it must be equal to or greater than
width times bytes required for Color_Type.
Pixel buffer size should be height times rowBytes.
#Param width pixel column count on Raster_Surface created; must be zero or greater ##
#Param height pixel row count on Raster_Surface created; must be zero or greater ##
#Param pixels pointer to destination pixels buffer; buffer size should be height
times rowBytes
##
#Param rowBytes interval from one Surface row to the next, or zero
##
#Return Canvas if all parameters are valid; otherwise, nullptr ##
#Example
#Description
Allocates a three by three bitmap, clears it to white, and draws a black pixel
in the center.
##
void draw(SkCanvas* ) {
const int width = 3;
const int height = 3;
SkPMColor pixels[height][width]; // allocate a 3x3 Premultiplied bitmap on the stack
// create a SkCanvas backed by a raster device, and delete it when the
// function goes out of scope.
std::unique_ptr<SkCanvas> canvas = SkCanvas::MakeRasterDirectN32(
width,
height,
pixels[0], // top-left of the bitmap
sizeof(pixels[0])); // byte width of the each row
// write a Premultiplied value for white into all pixels in the bitmap
canvas->clear(SK_ColorWHITE);
SkPMColor pmWhite = pixels[0][0]; // the Premultiplied format may vary
SkPaint paint; // by default, draws black
canvas->drawPoint(1, 1, paint); // draw in the center
canvas->flush(); // ensure that pixels is ready to be read
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
SkDebugf("%c", pixels[y][x] == pmWhite ? '-' : 'x');
}
SkDebugf("\n");
}
}
#StdOut
---
-x-
---
##
##
#SeeAlso MakeRasterDirect SkSurface::MakeRasterDirect SkImageInfo::MakeN32Premul
##
# ------------------------------------------------------------------------------
#Method SkCanvas()
#Line # creates with no Surface, no dimensions ##
Creates an empty Canvas with no backing device or pixels, with
a width and height of zero.
#Return empty Canvas ##
#Example
#Description
Passes a placeholder to a function that requires one.
##
#Function
// Returns true if either the canvas rotates the text by 90 degrees, or the paint does.
static void check_for_up_and_down_text(const SkCanvas* canvas, const SkPaint& paint) {
bool paintHasVertical = paint.isVerticalText();
const SkMatrix& matrix = canvas->getTotalMatrix();
bool matrixIsVertical = matrix.preservesRightAngles() && !matrix.isScaleTranslate();
SkDebugf("paint draws text %s\n", paintHasVertical != matrixIsVertical ?
"top to bottom" : "left to right");
}
static void check_for_up_and_down_text(const SkPaint& paint) {
SkCanvas canvas; // placeholder only, does not have an associated device
check_for_up_and_down_text(&canvas, paint);
}
##
void draw(SkCanvas* canvas) {
SkPaint paint;
check_for_up_and_down_text(paint); // paint draws text left to right
paint.setVerticalText(true);
check_for_up_and_down_text(paint); // paint draws text top to bottom
paint.setVerticalText(false);
canvas->rotate(90);
check_for_up_and_down_text(canvas, paint); // paint draws text top to bottom
}
#StdOut
paint draws text left to right
paint draws text top to bottom
paint draws text top to bottom
##
##
#SeeAlso MakeRasterDirect SkRasterHandleAllocator::MakeCanvas SkSurface::getCanvas SkCreateColorSpaceXformCanvas
##
# ------------------------------------------------------------------------------
#Method SkCanvas(int width, int height, const SkSurfaceProps* props = nullptr)
#Line # creates with no Surface, set dimensions, Surface_Properties ##
Creates Canvas of the specified dimensions without a Surface.
Used by Subclasses with custom implementations for draw member functions.
If props equals nullptr, Surface_Properties are created with
Surface_Properties_Legacy_Font_Host settings, which choose the pixel striping
direction and order. Since a platform may dynamically change its direction when
the device is rotated, and since a platform may have multiple monitors with
different characteristics, it is best not to rely on this legacy behavior.
#Param width zero or greater ##
#Param height zero or greater ##
#Param props LCD striping orientation and setting for device independent fonts;
may be nullptr
##
#Return Canvas placeholder with dimensions ##
#Example
SkCanvas canvas(10, 20); // 10 units wide, 20 units high
canvas.clipRect(SkRect::MakeXYWH(30, 40, 5, 10)); // clip is outside canvas' device
SkDebugf("canvas %s empty\n", canvas.getDeviceClipBounds().isEmpty() ? "is" : "is not");
#StdOut
canvas is empty
##
##
#SeeAlso MakeRasterDirect SkSurfaceProps SkPixelGeometry SkCreateColorSpaceXformCanvas
##
# ------------------------------------------------------------------------------
#Method explicit SkCanvas(sk_sp<SkBaseDevice> device)
#Deprecated soon
##
# ------------------------------------------------------------------------------
#Method explicit SkCanvas(const SkBitmap& bitmap)
#Line # uses existing Bitmap ##
Constructs a canvas that draws into bitmap.
Sets SkSurfaceProps::kLegacyFontHost_InitType in constructed Surface.
Bitmap is copied so that subsequently editing bitmap will not affect
constructed Canvas.
May be deprecated in the future.
#ToDo Should be deprecated? ##
#Param bitmap width, height, Color_Type, Alpha_Type, and pixel
storage of Raster_Surface
##
#Return Canvas that can be used to draw into bitmap ##
#Example
#Description
The actual output depends on the installed fonts.
##
SkBitmap bitmap;
// create a bitmap 5 wide and 11 high
bitmap.allocPixels(SkImageInfo::MakeN32Premul(5, 11));
SkCanvas canvas(bitmap);
canvas.clear(SK_ColorWHITE); // white is Unpremultiplied, in ARGB order
SkPixmap pixmap; // provides guaranteed access to the drawn pixels
if (!canvas.peekPixels(&pixmap)) {
SkDebugf("peekPixels should never fail.\n");
}
const SkPMColor* pixels = pixmap.addr32(); // points to top-left of bitmap
SkPMColor pmWhite = pixels[0]; // the Premultiplied format may vary
SkPaint paint; // by default, draws black, 12 point text
canvas.drawString("!", 1, 10, paint); // 1 char at baseline (1, 10)
for (int y = 0; y < bitmap.height(); ++y) {
for (int x = 0; x < bitmap.width(); ++x) {
SkDebugf("%c", *pixels++ == pmWhite ? '-' : 'x');
}
SkDebugf("\n");
}
#StdOut
-----
---x-
---x-
---x-
---x-
---x-
---x-
-----
---x-
---x-
-----
#StdOut ##
##
#SeeAlso MakeRasterDirect SkRasterHandleAllocator::MakeCanvas SkSurface::getCanvas SkCreateColorSpaceXformCanvas
##
#EnumClass ColorBehavior
#Line # exists for Android framework only ##
#Private
Android framework only.
##
#Code
enum class ColorBehavior {
kLegacy,
};
##
#Const kLegacy 0
#Line # placeholder ##
Is a placeholder to allow specialized constructor; has no meaning.
##
##
#Method SkCanvas(const SkBitmap& bitmap, ColorBehavior behavior)
#Line # exists for Android framework only ##
For use by Android framework only.
#Param bitmap specifies a bitmap for the canvas to draw into ##
#Param behavior specializes this constructor; value is unused ##
#Return Canvas that can be used to draw into bitmap ##
#NoExample
##
##
# ------------------------------------------------------------------------------
#Method SkCanvas(const SkBitmap& bitmap, const SkSurfaceProps& props)
#Line # uses existing Bitmap and Surface_Properties ##
Constructs a canvas that draws into bitmap.
Use props to match the device characteristics, like LCD striping.
bitmap is copied so that subsequently editing bitmap will not affect
constructed Canvas.
#Param bitmap width, height, Color_Type, Alpha_Type,
and pixel storage of Raster_Surface
##
#Param props order and orientation of RGB striping; and whether to use
device independent fonts
##
#Return Canvas that can be used to draw into bitmap ##
#Example
#Description
The actual output depends on the installed fonts.
##
SkBitmap bitmap;
// create a bitmap 5 wide and 11 high
bitmap.allocPixels(SkImageInfo::MakeN32Premul(5, 11));
SkCanvas canvas(bitmap, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
canvas.clear(SK_ColorWHITE); // white is Unpremultiplied, in ARGB order
SkPixmap pixmap; // provides guaranteed access to the drawn pixels
if (!canvas.peekPixels(&pixmap)) {
SkDebugf("peekPixels should never fail.\n");
}
const SkPMColor* pixels = pixmap.addr32(); // points to top-left of bitmap
SkPMColor pmWhite = pixels[0]; // the Premultiplied format may vary
SkPaint paint; // by default, draws black, 12 point text
canvas.drawString("!", 1, 10, paint); // 1 char at baseline (1, 10)
for (int y = 0; y < bitmap.height(); ++y) {
for (int x = 0; x < bitmap.width(); ++x) {
SkDebugf("%c", *pixels++ == pmWhite ? '-' : 'x');
}
SkDebugf("\n");
}
#StdOut
-----
---x-
---x-
---x-
---x-
---x-
---x-
-----
---x-
---x-
-----
#StdOut ##
##
#SeeAlso MakeRasterDirect SkRasterHandleAllocator::MakeCanvas SkSurface::getCanvas SkCreateColorSpaceXformCanvas
##
# ------------------------------------------------------------------------------
#Method virtual ~SkCanvas()
#Line # draws saved Layers, frees resources ##
Draws saved Layers, if any.
Frees up resources used by Canvas.
#Example
#Description
Canvas Layer draws into bitmap. saveLayerAlpha sets up an additional
drawing surface that blends with the bitmap. When Layer goes out of
scope, Layer Destructor is called. The saved Layer is restored, drawing
transparent letters.
##
void draw(SkCanvas* canvas) {
SkBitmap bitmap;
bitmap.allocPixels(SkImageInfo::MakeN32Premul(200, 200));
{
SkCanvas offscreen(bitmap);
SkPaint paint;
paint.setTextSize(100);
offscreen.drawString("ABC", 20, 160, paint);
SkRect layerBounds = SkRect::MakeXYWH(32, 32, 192, 192);
offscreen.saveLayerAlpha(&layerBounds, 128);
offscreen.clear(SK_ColorWHITE);
offscreen.drawString("DEF", 20, 160, paint);
}
canvas->drawBitmap(bitmap, 0, 0, nullptr);
}
##
#SeeAlso State_Stack
##
# ------------------------------------------------------------------------------
#Subtopic Property
#Populate
#Line # metrics and attributes ##
##
#Method SkMetaData& getMetaData()
#In Property
#In Utility
#Line # associates additional data with the canvas ##
Returns storage to associate additional data with the canvas.
The storage is freed when Canvas is deleted.
#Return storage that can be read from and written to ##
#Example
const char* kHelloMetaData = "HelloMetaData";
SkCanvas canvas;
SkMetaData& metaData = canvas.getMetaData();
SkDebugf("before: %s\n", metaData.findString(kHelloMetaData));
metaData.setString(kHelloMetaData, "Hello!");
SkDebugf("during: %s\n", metaData.findString(kHelloMetaData));
metaData.removeString(kHelloMetaData);
SkDebugf("after: %s\n", metaData.findString(kHelloMetaData));
#StdOut
before: (null)
during: Hello!
after: (null)
#StdOut ##
##
#SeeAlso SkMetaData
##
# ------------------------------------------------------------------------------
#Method SkImageInfo imageInfo() const
#In Property
#Line # returns Image_Info for Canvas ##
Returns Image_Info for Canvas. If Canvas is not associated with Raster_Surface or
GPU_Surface, returned Color_Type is set to kUnknown_SkColorType.
#Return dimensions and Color_Type of Canvas ##
#Example
SkCanvas emptyCanvas;
SkImageInfo canvasInfo = emptyCanvas.imageInfo();
SkImageInfo emptyInfo;
SkDebugf("emptyInfo %c= canvasInfo\n", emptyInfo == canvasInfo ? '=' : '!');
#StdOut
emptyInfo == canvasInfo
##
##
#SeeAlso SkImageInfo MakeRasterDirect makeSurface
##
# ------------------------------------------------------------------------------
#Method bool getProps(SkSurfaceProps* props) const
#In Property
#Line # copies Surface_Properties if available ##
Copies Surface_Properties, if Canvas is associated with Raster_Surface or
GPU_Surface, and returns true. Otherwise, returns false and leave props unchanged.
#Param props storage for writable SkSurfaceProps ##
#Return true if Surface_Properties was copied ##
#ToDo This seems old style. Deprecate? ##
#Example
SkBitmap bitmap;
SkCanvas canvas(bitmap, SkSurfaceProps(0, kRGB_V_SkPixelGeometry));
SkSurfaceProps surfaceProps(0, kUnknown_SkPixelGeometry);
SkDebugf("isRGB:%d\n", SkPixelGeometryIsRGB(surfaceProps.pixelGeometry()));
if (!canvas.getProps(&surfaceProps)) {
SkDebugf("getProps failed unexpectedly.\n");
}
SkDebugf("isRGB:%d\n", SkPixelGeometryIsRGB(surfaceProps.pixelGeometry()));
#StdOut
isRGB:0
isRGB:1
#StdOut ##
##
#SeeAlso SkSurfaceProps makeSurface
##
# ------------------------------------------------------------------------------
#Subtopic Utility
#Populate
#Line # rarely called management functions ##
##
#Method void flush()
#In Utility
#Line # triggers execution of all pending draw operations ##
Triggers the immediate execution of all pending draw operations.
If Canvas is associated with GPU_Surface, resolves all pending GPU operations.
If Canvas is associated with Raster_Surface, has no effect; raster draw
operations are never deferred.
#ToDo
In an overview section on managing the GPU, include:
- flush should never change what is drawn
- call to kick off gpu work
- calling too much impacts performance
- some calls (peekPixels, prepareForExternalIO) call it internally
- canvas call is local, GrContext::flush is global
- diffentiate between flush, flushAndSignalSemaphores
- normally never needs to be called
- call it when sharing gpu resources, feeling memory pressure, swapping out app, and before
abandoning context
- also call to say "I'm finished drawing here", e.g., when drawing to a GPU-backed offscreen surface
(created with SkSurface::MakeRenderTarget)
for posterity: this doesn't show a difference: fiddle.skia.org/c/@flushfail
##
#ToDo haven't thought of a useful example to put here ##
#NoExample
##
#SeeAlso peekPixels SkSurface::flush() GrContext::flush() SkSurface::prepareForExternalIO GrContext::abandonContext()
##
# ------------------------------------------------------------------------------
#Method virtual SkISize getBaseLayerSize() const
#In Property
#Line # returns size of base Layer in global coordinates ##
Gets the size of the base or root Layer in global canvas coordinates. The
origin of the base Layer is always (0,0). The area available for drawing may be
smaller (due to clipping or saveLayer).
#Return integral width and height of base Layer ##
#Example
SkBitmap bitmap;
bitmap.allocPixels(SkImageInfo::MakeN32Premul(20, 30));
SkCanvas canvas(bitmap, SkSurfaceProps(0, kUnknown_SkPixelGeometry));
canvas.clipRect(SkRect::MakeWH(10, 40));
SkIRect clipDeviceBounds = canvas.getDeviceClipBounds();
if (clipDeviceBounds.isEmpty()) {
SkDebugf("Empty clip bounds is unexpected!\n");
}
SkDebugf("clip=%d,%d\n", clipDeviceBounds.width(), clipDeviceBounds.height());
SkISize baseLayerSize = canvas.getBaseLayerSize();
SkDebugf("size=%d,%d\n", baseLayerSize.width(), baseLayerSize.height());
#StdOut
clip=10,30
size=20,30
##
##
#ToDo is this the same as the width and height of surface? ##
#SeeAlso getDeviceClipBounds
##
# ------------------------------------------------------------------------------
#Method sk_sp<SkSurface> makeSurface(const SkImageInfo& info, const SkSurfaceProps* props = nullptr)
#In Constructor
#Line # creates Surface matching SkImageInfo and SkSurfaceProps ##
Creates Surface matching info and props, and associates it with Canvas.
Returns nullptr if no match found.
If props is nullptr, matches Surface_Properties in Canvas. If props is nullptr and Canvas
does not have Surface_Properties, creates Surface with default Surface_Properties.
#Param info width, height, Color_Type, Alpha_Type, and Color_Space ##
#Param props Surface_Properties to match; may be nullptr to match Canvas ##
#Return Surface matching info and props, or nullptr if no match is available ##
#Example
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(5, 6);
SkCanvas* smallCanvas = surface->getCanvas();
SkImageInfo imageInfo = SkImageInfo::MakeN32Premul(3, 4);
sk_sp<SkSurface> compatible = smallCanvas->makeSurface(imageInfo);
SkDebugf("compatible %c= nullptr\n", compatible == nullptr ? '=' : '!');
SkDebugf("size = %d, %d\n", compatible->width(), compatible->height());
#StdOut
compatible != nullptr
size = 3, 4
##
##
#SeeAlso SkSurface SkSurface::makeSurface SkImageInfo SkSurfaceProps
##
# ------------------------------------------------------------------------------
#Method virtual GrContext* getGrContext()
#In Property
#Line # returns GPU_Context of the GPU_Surface ##
Returns GPU_Context of the GPU_Surface associated with Canvas.
#Return GPU_Context, if available; nullptr otherwise ##
#Example
void draw(SkCanvas* canvas) {
if (canvas->getGrContext()) {
canvas->clear(SK_ColorRED);
} else {
canvas->clear(SK_ColorBLUE);
}
}
##
#ToDo fiddle should show both CPU and GPU out ##
#SeeAlso GrContext
##
# ------------------------------------------------------------------------------
#Method void* accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes, SkIPoint* origin = nullptr)
#In Utility
#In Property
#Line # returns writable pixel access if available ##
Returns the pixel base address, Image_Info, rowBytes, and origin if the pixels
can be read directly. The returned address is only valid
while Canvas is in scope and unchanged. Any Canvas call or Surface call
may invalidate the returned address and other returned values.
If pixels are inaccessible, info, rowBytes, and origin are unchanged.
#Param info storage for writable pixels' Image_Info; may be nullptr ##
#Param rowBytes storage for writable pixels' row bytes; may be nullptr ##
#Param origin storage for Canvas top Layer origin, its top-left corner;
may be nullptr
##
#Return address of pixels, or nullptr if inaccessible ##
#Example
void draw(SkCanvas* canvas) {
if (canvas->accessTopLayerPixels(nullptr, nullptr)) {
canvas->clear(SK_ColorRED);
} else {
canvas->clear(SK_ColorBLUE);
}
}
##
#Example
#Description
Draws "ABC" on the device. Then draws "DEF" in Layer, and reads
Layer to add a large dotted "DEF". Finally blends Layer with the
device.
The Layer and blended result appear on the CPU and GPU but the large dotted
"DEF" appear only on the CPU.
##
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setTextSize(100);
canvas->drawString("ABC", 20, 160, paint);
SkRect layerBounds = SkRect::MakeXYWH(32, 32, 192, 192);
canvas->saveLayerAlpha(&layerBounds, 128);
canvas->clear(SK_ColorWHITE);
canvas->drawString("DEF", 20, 160, paint);
SkImageInfo imageInfo;
size_t rowBytes;
SkIPoint origin;
uint32_t* access = (uint32_t*) canvas->accessTopLayerPixels(&imageInfo, &rowBytes, &origin);
if (access) {
int h = imageInfo.height();
int v = imageInfo.width();
int rowWords = rowBytes / sizeof(uint32_t);
for (int y = 0; y < h; ++y) {
int newY = (y - h / 2) * 2 + h / 2;
if (newY < 0 || newY >= h) {
continue;
}
for (int x = 0; x < v; ++x) {
int newX = (x - v / 2) * 2 + v / 2;
if (newX < 0 || newX >= v) {
continue;
}
if (access[y * rowWords + x] == SK_ColorBLACK) {
access[newY * rowWords + newX] = SK_ColorGRAY;
}
}
}
}
canvas->restore();
}
##
#ToDo there are no callers of this that I can find. Deprecate? ##
#ToDo fiddle should show both CPU and GPU out ##
#SeeAlso SkImageInfo SkPixmap
##
# ------------------------------------------------------------------------------
#Method SkRasterHandleAllocator::Handle accessTopRasterHandle() const
#In Utility
#In Property
#Line # returns context that tracks Clip and Matrix ##
Returns custom context that tracks the Matrix and Clip.
Use Raster_Handle_Allocator to blend Skia drawing with custom drawing, typically performed
by the host platform user interface. The custom context returned is generated by
SkRasterHandleAllocator::MakeCanvas, which creates a custom canvas with raster storage for
the drawing destination.
#Return context of custom allocation ##
#Example
#Description
#ToDo ##
##
#Function
static void DeleteCallback(void*, void* context) {
delete (char*) context;
}
class CustomAllocator : public SkRasterHandleAllocator {
public:
bool allocHandle(const SkImageInfo& info, Rec* rec) override {
char* context = new char[4]{'s', 'k', 'i', 'a'};
rec->fReleaseProc = DeleteCallback;
rec->fReleaseCtx = context;
rec->fHandle = context;
rec->fPixels = context;
rec->fRowBytes = 4;
return true;
}
void updateHandle(Handle handle, const SkMatrix& ctm, const SkIRect& clip_bounds) override {
// apply canvas matrix and clip to custom environment
}
};
##
void draw(SkCanvas* canvas) {
const SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
std::unique_ptr<SkCanvas> c2 =
SkRasterHandleAllocator::MakeCanvas(std::unique_ptr<CustomAllocator>(
new CustomAllocator()), info);
char* context = (char*) c2->accessTopRasterHandle();
SkDebugf("context = %.4s\n", context);
}
#StdOut
context = skia
##
#ToDo skstd::make_unique could not be used because def is private -- note to fix in c++14? ##
##
#SeeAlso SkRasterHandleAllocator
##
# ------------------------------------------------------------------------------
#Subtopic Pixels
#Populate
#Line # read and write pixel values ##
##
#Method bool peekPixels(SkPixmap* pixmap)
#In Pixels
#Line # returns if Canvas has direct access to its pixels ##
Returns true if Canvas has direct access to its pixels.
Pixels are readable when Device is raster. Pixels are not readable when Canvas
is returned from GPU_Surface, returned by SkDocument::beginPage, returned by
SkPictureRecorder::beginRecording, or Canvas is the base of a utility class
like SkDebugCanvas.
pixmap is valid only while Canvas is in scope and unchanged. Any
Canvas or Surface call may invalidate the pixmap values.
#Param pixmap storage for pixel state if pixels are readable; otherwise, ignored ##
#Return true if Canvas has direct access to pixels ##
#Example
SkPixmap pixmap;
if (canvas->peekPixels(&pixmap)) {
SkDebugf("width=%d height=%d\n", pixmap.bounds().width(), pixmap.bounds().height());
}
#StdOut
width=256 height=256
##
##
#SeeAlso readPixels SkBitmap::peekPixels SkImage::peekPixels SkSurface::peekPixels
##
# ------------------------------------------------------------------------------
#Method bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
int srcX, int srcY)
#In Pixels
#Line # copies and converts rectangle of pixels from Canvas ##
Copies Rect of pixels from Canvas into dstPixels. Matrix and Clip are
ignored.
Source Rect corners are (srcX, srcY) and (imageInfo().width(), imageInfo().height()).
Destination Rect corners are (0, 0) and (dstInfo.width(), dstInfo.height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to dstInfo.colorType() and dstInfo.alphaType() if required.
Pixels are readable when Device is raster, or backed by a GPU.
Pixels are not readable when SkCanvas is returned by SkDocument::beginPage,
returned by SkPictureRecorder::beginRecording, or Canvas is the base of a utility
class like SkDebugCanvas.
The destination pixel storage must be allocated by the caller.
Pixel values are converted only if Color_Type and Alpha_Type
do not match. Only pixels within both source and destination rectangles
are copied. dstPixels contents outside Rect intersection are unchanged.
Pass negative values for srcX or srcY to offset pixels across or down destination.
Does not copy, and returns false if:
#List
# Source and destination rectangles do not intersect. ##
# Canvas pixels could not be converted to dstInfo.colorType() or dstInfo.alphaType(). ##
# Canvas pixels are not readable; for instance, Canvas is document-based. ##
# dstRowBytes is too small to contain one row of pixels. ##
##
#Param dstInfo width, height, Color_Type, and Alpha_Type of dstPixels ##
#Param dstPixels storage for pixels; dstInfo.height() times dstRowBytes, or larger ##
#Param dstRowBytes size of one destination row; dstInfo.width() times pixel size, or larger ##
#Param srcX offset into readable pixels on x-axis; may be negative ##
#Param srcY offset into readable pixels on y-axis; may be negative ##
#Return true if pixels were copied ##
#Example
#Width 64
#Height 64
#Description
A black circle drawn on a blue background provides an image to copy.
readPixels copies one quarter of the canvas into each of the four corners.
The copied quarter circles overdraw the original circle.
##
canvas->clear(SK_ColorBLUE);
SkPaint paint;
canvas->drawCircle(32, 32, 28, paint);
SkImageInfo info = SkImageInfo::Make(64, 64, kBGRA_8888_SkColorType, kPremul_SkAlphaType);
sk_sp<SkData> data(SkData::MakeUninitialized(info.minRowBytes() * info.height()));
sk_bzero(data->writable_data(), info.minRowBytes() * info.height());
for (int x : { 32, -32 } ) {
for (int y : { 32, -32 } ) {
canvas->readPixels(info, data->writable_data(), info.minRowBytes(), x, y);
}
}
sk_sp<SkImage> image = SkImage::MakeRasterData(info, data, info.minRowBytes());
canvas->drawImage(image, 0, 0);
##
#Example
#Description
Canvas returned by Raster_Surface has Premultiplied pixel values.
clear() takes Unpremultiplied input with Color_Alpha equal 0x80
and RGB equal 0x55, 0xAA, 0xFF. RGB is multiplied by Color_Alpha
to generate Premultiplied value 0x802B5580. readPixels converts pixel back
to Unpremultiplied value 0x8056A9FF, introducing error.
##
canvas->clear(0x8055aaff);
for (SkAlphaType alphaType : { kPremul_SkAlphaType, kUnpremul_SkAlphaType } ) {
uint32_t pixel = 0;
SkImageInfo info = SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, alphaType);
if (canvas->readPixels(info, &pixel, 4, 0, 0)) {
SkDebugf("pixel = %08x\n", pixel);
}
}
#StdOut
pixel = 802b5580
pixel = 8056a9ff
##
##
#SeeAlso peekPixels writePixels drawBitmap drawImage SkBitmap::readPixels SkPixmap::readPixels SkImage::readPixels SkSurface::readPixels
##
# ------------------------------------------------------------------------------
#Method bool readPixels(const SkPixmap& pixmap, int srcX, int srcY)
Copies Rect of pixels from Canvas into pixmap. Matrix and Clip are
ignored.
Source Rect corners are (srcX, srcY) and (imageInfo().width(), imageInfo().height()).
Destination Rect corners are (0, 0) and (pixmap.width(), pixmap.height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to pixmap.colorType() and pixmap.alphaType() if required.
Pixels are readable when Device is raster, or backed by a GPU.
Pixels are not readable when SkCanvas is returned by SkDocument::beginPage,
returned by SkPictureRecorder::beginRecording, or Canvas is the base of a utility
class like SkDebugCanvas.
Caller must allocate pixel storage in pixmap if needed.
Pixel values are converted only if Color_Type and Alpha_Type
do not match. Only pixels within both source and destination Rects
are copied. pixmap pixels contents outside Rect intersection are unchanged.
Pass negative values for srcX or srcY to offset pixels across or down pixmap.
Does not copy, and returns false if:
#List
# Source and destination rectangles do not intersect. ##
# Canvas pixels could not be converted to pixmap.colorType() or pixmap.alphaType(). ##
# Canvas pixels are not readable; for instance, Canvas is document-based. ##
# Pixmap pixels could not be allocated. ##
# pixmap.rowBytes() is too small to contain one row of pixels. ##
##
#Param pixmap storage for pixels copied from Canvas ##
#Param srcX offset into readable pixels on x-axis; may be negative ##
#Param srcY offset into readable pixels on y-axis; may be negative ##
#Return true if pixels were copied ##
#Example
#Description
clear() takes Unpremultiplied input with Color_Alpha equal 0x80
and RGB equal 0x55, 0xAA, 0xFF. RGB is multiplied by Color_Alpha
to generate Premultiplied value 0x802B5580.
##
void draw(SkCanvas* canvas) {
canvas->clear(0x8055aaff);
uint32_t pixels[1] = { 0 };
SkPixmap pixmap(SkImageInfo::MakeN32Premul(1, 1), pixels, 4);
canvas->readPixels(pixmap, 0, 0);
SkDebugf("pixel = %08x\n", pixels[0]);
}
#StdOut
pixel = 802b5580
##
##
#SeeAlso peekPixels writePixels drawBitmap drawImage SkBitmap::readPixels SkPixmap::readPixels SkImage::readPixels SkSurface::readPixels
##
# ------------------------------------------------------------------------------
#Method bool readPixels(const SkBitmap& bitmap, int srcX, int srcY)
Copies Rect of pixels from Canvas into bitmap. Matrix and Clip are
ignored.
Source Rect corners are (srcX, srcY) and (imageInfo().width(), imageInfo().height()).
Destination Rect corners are (0, 0) and (bitmap.width(), bitmap.height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to bitmap.colorType() and bitmap.alphaType() if required.
Pixels are readable when Device is raster, or backed by a GPU.
Pixels are not readable when SkCanvas is returned by SkDocument::beginPage,
returned by SkPictureRecorder::beginRecording, or Canvas is the base of a utility
class like SkDebugCanvas.
Caller must allocate pixel storage in bitmap if needed.
Bitmap values are converted only if Color_Type and Alpha_Type
do not match. Only pixels within both source and destination rectangles
are copied. Bitmap pixels outside Rect intersection are unchanged.
Pass negative values for srcX or srcY to offset pixels across or down bitmap.
Does not copy, and returns false if:
#List
# Source and destination rectangles do not intersect. ##
# Canvas pixels could not be converted to bitmap.colorType() or bitmap.alphaType(). ##
# Canvas pixels are not readable; for instance, Canvas is document-based. ##
# bitmap pixels could not be allocated. ##
# bitmap.rowBytes() is too small to contain one row of pixels. ##
##
#Param bitmap storage for pixels copied from Canvas ##
#Param srcX offset into readable pixels on x-axis; may be negative ##
#Param srcY offset into readable pixels on y-axis; may be negative ##
#Return true if pixels were copied ##
#Example
#Description
clear() takes Unpremultiplied input with Color_Alpha equal 0x80
and RGB equal 0x55, 0xAA, 0xFF. RGB is multiplied by Color_Alpha
to generate Premultiplied value 0x802B5580.
##
void draw(SkCanvas* canvas) {
canvas->clear(0x8055aaff);
SkBitmap bitmap;
bitmap.allocPixels(SkImageInfo::MakeN32Premul(1, 1));
canvas->readPixels(bitmap, 0, 0);
SkDebugf("pixel = %08x\n", bitmap.getAddr32(0, 0)[0]);
}
#StdOut
pixel = 802b5580
##
##
#SeeAlso peekPixels writePixels drawBitmap drawImage SkBitmap::readPixels SkPixmap::readPixels SkImage::readPixels SkSurface::readPixels
##
# ------------------------------------------------------------------------------
#Method bool writePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes, int x, int y)
#In Pixels
#Line # copies and converts rectangle of pixels to Canvas ##
Copies Rect from pixels to Canvas. Matrix and Clip are ignored.
Source Rect corners are (0, 0) and (info.width(), info.height()).
Destination Rect corners are (x, y) and
(imageInfo().width(), imageInfo().height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to imageInfo().colorType() and imageInfo().alphaType() if required.
Pixels are writable when Device is raster, or backed by a GPU.
Pixels are not writable when SkCanvas is returned by SkDocument::beginPage,
returned by SkPictureRecorder::beginRecording, or Canvas is the base of a utility
class like SkDebugCanvas.
Pixel values are converted only if Color_Type and Alpha_Type
do not match. Only pixels within both source and destination rectangles
are copied. Canvas pixels outside Rect intersection are unchanged.
Pass negative values for x or y to offset pixels to the left or
above Canvas pixels.
Does not copy, and returns false if:
#List
# Source and destination rectangles do not intersect. ##
# pixels could not be converted to Canvas imageInfo().colorType() or
imageInfo().alphaType(). ##
# Canvas pixels are not writable; for instance, Canvas is document-based. ##
# rowBytes is too small to contain one row of pixels. ##
##
#Param info width, height, Color_Type, and Alpha_Type of pixels ##
#Param pixels pixels to copy, of size info.height() times rowBytes, or larger ##
#Param rowBytes size of one row of pixels; info.width() times pixel size, or larger ##
#Param x offset into Canvas writable pixels on x-axis; may be negative ##
#Param y offset into Canvas writable pixels on y-axis; may be negative ##
#Return true if pixels were written to Canvas ##
#Example
SkImageInfo imageInfo = SkImageInfo::MakeN32(256, 1, kPremul_SkAlphaType);
for (int y = 0; y < 256; ++y) {
uint32_t pixels[256];
for (int x = 0; x < 256; ++x) {
pixels[x] = SkColorSetARGB(x, x + y, x, x - y);
}
canvas->writePixels(imageInfo, &pixels, sizeof(pixels), 0, y);
}
##
#SeeAlso readPixels drawBitmap drawImage SkBitmap::writePixels
##
# ------------------------------------------------------------------------------
#Method bool writePixels(const SkBitmap& bitmap, int x, int y)
Copies Rect from pixels to Canvas. Matrix and Clip are ignored.
Source Rect corners are (0, 0) and (bitmap.width(), bitmap.height()).
Destination Rect corners are (x, y) and
(imageInfo().width(), imageInfo().height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to imageInfo().colorType() and imageInfo().alphaType() if required.
Pixels are writable when Device is raster, or backed by a GPU.
Pixels are not writable when SkCanvas is returned by SkDocument::beginPage,
returned by SkPictureRecorder::beginRecording, or Canvas is the base of a utility
class like SkDebugCanvas.
Pixel values are converted only if Color_Type and Alpha_Type
do not match. Only pixels within both source and destination rectangles
are copied. Canvas pixels outside Rect intersection are unchanged.
Pass negative values for x or y to offset pixels to the left or
above Canvas pixels.
Does not copy, and returns false if:
#List
# Source and destination rectangles do not intersect. ##
# bitmap does not have allocated pixels. ##
# bitmap pixels could not be converted to Canvas imageInfo().colorType() or
imageInfo().alphaType(). ##
# Canvas pixels are not writable; for instance, Canvas is document based. ##
# bitmap pixels are inaccessible; for instance, bitmap wraps a texture. ##
##
#Param bitmap contains pixels copied to Canvas ##
#Param x offset into Canvas writable pixels in x; may be negative ##
#Param y offset into Canvas writable pixels in y; may be negative ##
#Return true if pixels were written to Canvas ##
#Example
void draw(SkCanvas* canvas) {
SkImageInfo imageInfo = SkImageInfo::MakeN32Premul(2, 2);
SkBitmap bitmap;
bitmap.setInfo(imageInfo);
uint32_t pixels[4];
bitmap.setPixels(pixels);
for (int y = 0; y < 256; y += 2) {
for (int x = 0; x < 256; x += 2) {
pixels[0] = SkColorSetRGB(x, y, x | y);
pixels[1] = SkColorSetRGB(x ^ y, y, x);
pixels[2] = SkColorSetRGB(x, x & y, y);
pixels[3] = SkColorSetRGB(~x, ~y, x);
canvas->writePixels(bitmap, x, y);
}
}
}
##
#SeeAlso readPixels drawBitmap drawImage SkBitmap::writePixels
##
# ------------------------------------------------------------------------------
#Subtopic State_Stack
#Line # stack of state for hierarchical drawing ##
Canvas maintains a stack of state that allows hierarchical drawing, commonly used
to implement windows and views. The initial state has an identity matrix and and
an infinite clip. Even with a wide-open clip, drawing is constrained by the
bounds of the Canvas Surface or Device.
Canvas savable state consists of Clip and Matrix.
Clip describes the area that may be drawn to.
Matrix transforms the geometry.
save(), saveLayer, saveLayerPreserveLCDTextRequests, and saveLayerAlpha
save state and return the depth of the stack.
restore(), restoreToCount, and ~SkCanvas() revert state to its value when saved.
Each state on the stack intersects Clip with the previous Clip,
and concatenates Matrix with the previous Matrix.
The intersected Clip makes the drawing area the same or smaller;
the concatenated Matrix may move the origin and potentially scale or rotate
the coordinate space.
Canvas does not require balancing the state stack but it is a good idea
to do so. Calling save() without restore() will eventually cause Skia to fail;
mismatched save() and restore() create hard to find bugs.
It is not possible to use state to draw outside of the clip defined by the
previous state.
#Example
#Description
Draw to ever smaller clips; then restore drawing to full canvas.
Note that the second clipRect is not permitted to enlarge Clip.
##
#Height 160
void draw(SkCanvas* canvas) {
SkPaint paint;
canvas->save(); // records stack depth to restore
canvas->clipRect(SkRect::MakeWH(100, 100)); // constrains drawing to clip
canvas->clear(SK_ColorRED); // draws to limit of clip
canvas->save(); // records stack depth to restore
canvas->clipRect(SkRect::MakeWH(50, 150)); // Rect below 100 is ignored
canvas->clear(SK_ColorBLUE); // draws to smaller clip
canvas->restore(); // enlarges clip
canvas->drawLine(20, 20, 150, 150, paint); // line below 100 is not drawn
canvas->restore(); // enlarges clip
canvas->drawLine(150, 20, 50, 120, paint); // line below 100 is drawn
}
##
Each Clip uses the current Matrix for its coordinates.
#Example
#Description
While clipRect is given the same rectangle twice, Matrix makes the second
clipRect draw at half the size of the first.
##
#Height 128
void draw(SkCanvas* canvas) {
canvas->clipRect(SkRect::MakeWH(100, 100));
canvas->clear(SK_ColorRED);
canvas->scale(.5, .5);
canvas->clipRect(SkRect::MakeWH(100, 100));
canvas->clear(SK_ColorBLUE);
}
##
#SeeAlso save() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha restore() restoreToCount
#Method int save()
#In State_Stack
#Line # saves Clip and Matrix on stack ##
Saves Matrix and Clip.
Calling restore() discards changes to Matrix and Clip,
restoring the Matrix and Clip to their state when save() was called.
Matrix may be changed by translate(), scale(), rotate(), skew(), concat(), setMatrix,
and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion.
Saved Canvas state is put on a stack; multiple calls to save() should be balance
by an equal number of calls to restore().
Call restoreToCount with result to restore this and subsequent saves.
#Return depth of saved stack ##
#Example
#Description
The black square is translated 50 pixels down and to the right.
Restoring Canvas state removes translate() from Canvas stack;
the red square is not translated, and is drawn at the origin.
##
#Height 100
void draw(SkCanvas* canvas) {
SkPaint paint;
SkRect rect = { 0, 0, 25, 25 };
canvas->drawRect(rect, paint);
canvas->save();
canvas->translate(50, 50);
canvas->drawRect(rect, paint);
canvas->restore();
paint.setColor(SK_ColorRED);
canvas->drawRect(rect, paint);
}
##
#SeeAlso saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha restore() restoreToCount
##
# ------------------------------------------------------------------------------
#Method void restore()
#In State_Stack
#Line # restores changes to Clip and Matrix, pops save stack ##
Removes changes to Matrix and Clip since Canvas state was
last saved. The state is removed from the stack.
Does nothing if the stack is empty.
#Example
void draw(SkCanvas* canvas) {
SkCanvas simple;
SkDebugf("depth = %d\n", simple.getSaveCount());
simple.restore();
SkDebugf("depth = %d\n", simple.getSaveCount());
}
##
#SeeAlso save() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha restoreToCount
##
# ------------------------------------------------------------------------------
#Method int getSaveCount() const
#In State_Stack
#Line # returns depth of stack containing Clip and Matrix ##
Returns the number of saved states, each containing: Matrix and Clip.
Equals the number of save() calls less the number of restore() calls plus one.
The save count of a new canvas is one.
#Return depth of save state stack ##
#Example
void draw(SkCanvas* canvas) {
SkCanvas simple;
SkDebugf("depth = %d\n", simple.getSaveCount());
simple.save();
SkDebugf("depth = %d\n", simple.getSaveCount());
simple.restore();
SkDebugf("depth = %d\n", simple.getSaveCount());
}
#StdOut
depth = 1
depth = 2
depth = 1
##
##
#SeeAlso save() restore() restoreToCount
##
# ------------------------------------------------------------------------------
#Method void restoreToCount(int saveCount)
#In State_Stack
#Line # restores changes to Clip and Matrix to given depth ##
Restores state to Matrix and Clip values when save(), saveLayer,
saveLayerPreserveLCDTextRequests, or saveLayerAlpha returned saveCount.
Does nothing if saveCount is greater than state stack count.
Restores state to initial values if saveCount is less than or equal to one.
#Param saveCount depth of state stack to restore ##
#Example
void draw(SkCanvas* canvas) {
SkDebugf("depth = %d\n", canvas->getSaveCount());
canvas->save();
canvas->save();
SkDebugf("depth = %d\n", canvas->getSaveCount());
canvas->restoreToCount(0);
SkDebugf("depth = %d\n", canvas->getSaveCount());
}
#StdOut
depth = 1
depth = 3
depth = 1
##
##
#SeeAlso restore() getSaveCount save()
##
#Subtopic State_Stack ##
# ------------------------------------------------------------------------------
#Subtopic Layer
#Substitute layer
#Alias Layers
#Substitute layers
##
#Line # temporary Bitmap to draw into ##
Layer allocates a temporary Bitmap to draw into. When the drawing is
complete, the Bitmap is drawn into the Canvas.
Layer is saved in a stack along with other saved state. When state with a Layer
is restored, the Bitmap is drawn into the previous Layer.
Layer may be initialized with the contents of the previous Layer. When Layer is
restored, its Bitmap can be modified by Paint passed to Layer to apply
Color_Alpha, Color_Filter, Image_Filter, and Blend_Mode.
#Method int saveLayer(const SkRect* bounds, const SkPaint* paint)
#In Layer
#Line # saves Clip and Matrix on stack; creates Layer ##
Saves Matrix and Clip, and allocates a Bitmap for subsequent drawing.
Calling restore() discards changes to Matrix and Clip, and draws the Bitmap.
Matrix may be changed by translate(), scale(), rotate(), skew(), concat(),
setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect,
clipPath, clipRegion.
Rect bounds suggests but does not define the Bitmap size. To clip drawing to
a specific rectangle, use clipRect.
Optional Paint paint applies Color_Alpha, Color_Filter, Image_Filter, and
Blend_Mode when restore() is called.
Call restoreToCount with returned value to restore this and subsequent saves.
#Param bounds hint to limit the size of the Layer; may be nullptr ##
#Param paint graphics state for Layer; may be nullptr ##
#Return depth of saved stack ##
#Example
#Description
Rectangles are blurred by Image_Filter when restore() draws Layer to main
Canvas.
##
#Height 128
#Function
###$
#include "SkBlurImageFilter.h"
$$$#
##
void draw(SkCanvas* canvas) {
SkPaint paint, blur;
blur.setImageFilter(SkBlurImageFilter::Make(3, 3, nullptr));
canvas->saveLayer(nullptr, &blur);
SkRect rect = { 25, 25, 50, 50};
canvas->drawRect(rect, paint);
canvas->translate(50, 50);
paint.setColor(SK_ColorRED);
canvas->drawRect(rect, paint);
canvas->restore();
}
##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha SaveLayerRec
##
#Method int saveLayer(const SkRect& bounds, const SkPaint* paint)
#In Layer
Saves Matrix and Clip, and allocates a Bitmap for subsequent drawing.
Calling restore() discards changes to Matrix and Clip, and draws the Bitmap.
Matrix may be changed by translate(), scale(), rotate(), skew(), concat(),
setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect,
clipPath, clipRegion.
Rect bounds suggests but does not define the Layer size. To clip drawing to
a specific rectangle, use clipRect.
Optional Paint paint applies Color_Alpha, Color_Filter, Image_Filter, and
Blend_Mode when restore() is called.
Call restoreToCount with returned value to restore this and subsequent saves.
#Param bounds hint to limit the size of Layer; may be nullptr ##
#Param paint graphics state for Layer; may be nullptr ##
#Return depth of saved stack ##
#Example
#Description
Rectangles are blurred by Image_Filter when restore() draws Layer to main Canvas.
The red rectangle is clipped; it does not fully fit on Layer.
Image_Filter blurs past edge of Layer so red rectangle is blurred on all sides.
##
#Height 128
#Function
###$
#include "SkBlurImageFilter.h"
$$$#
##
void draw(SkCanvas* canvas) {
SkPaint paint, blur;
blur.setImageFilter(SkBlurImageFilter::Make(3, 3, nullptr));
canvas->saveLayer(SkRect::MakeWH(90, 90), &blur);
SkRect rect = { 25, 25, 50, 50};
canvas->drawRect(rect, paint);
canvas->translate(50, 50);
paint.setColor(SK_ColorRED);
canvas->drawRect(rect, paint);
canvas->restore();
}
##
#SeeAlso save() restore() saveLayerPreserveLCDTextRequests saveLayerAlpha SaveLayerRec
##
#Method int saveLayerPreserveLCDTextRequests(const SkRect* bounds, const SkPaint* paint)
#In Layer
#Line # saves Clip and Matrix on stack; creates Layer for LCD text ##
Saves Matrix and Clip, and allocates a Bitmap for subsequent drawing.
LCD_Text is preserved when the Layer is drawn to the prior Layer.
Calling restore() discards changes to Matrix and Clip, and draws Layer.
Matrix may be changed by translate(), scale(), rotate(), skew(), concat(),
setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect,
clipPath, clipRegion.
Rect bounds suggests but does not define the Layer size. To clip drawing to
a specific rectangle, use clipRect.
Optional Paint paint applies Color_Alpha, Color_Filter, Image_Filter, and
Blend_Mode when restore() is called.
Call restoreToCount with returned value to restore this and subsequent saves.
Draw text on an opaque background so that LCD_Text blends correctly with the
prior Layer. LCD_Text drawn on a background with transparency may result in
incorrect blending.
#Param bounds hint to limit the size of Layer; may be nullptr ##
#Param paint graphics state for Layer; may be nullptr ##
#Return depth of saved stack ##
#Example
SkPaint paint;
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
paint.setTextSize(20);
for (auto preserve : { false, true } ) {
preserve ? canvas->saveLayerPreserveLCDTextRequests(nullptr, nullptr)
: canvas->saveLayer(nullptr, nullptr);
SkPaint p;
p.setColor(SK_ColorWHITE);
// Comment out the next line to draw on a non-opaque background.
canvas->drawRect(SkRect::MakeLTRB(25, 40, 200, 70), p);
canvas->drawString("Hamburgefons", 30, 60, paint);
p.setColor(0xFFCCCCCC);
canvas->drawRect(SkRect::MakeLTRB(25, 70, 200, 100), p);
canvas->drawString("Hamburgefons", 30, 90, paint);
canvas->restore();
canvas->translate(0, 80);
}
##
#SeeAlso save() restore() saveLayer saveLayerAlpha SaveLayerRec
##
#Method int saveLayerAlpha(const SkRect* bounds, U8CPU alpha)
#In Layer
#Line # saves Clip and Matrix on stack; creates Layer; sets opacity ##
Saves Matrix and Clip, and allocates Bitmap for subsequent drawing.
Calling restore() discards changes to Matrix and Clip,
and blends Layer with alpha opacity onto prior Layer.
Matrix may be changed by translate(), scale(), rotate(), skew(), concat(),
setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect,
clipPath, clipRegion.
Rect bounds suggests but does not define Layer size. To clip drawing to
a specific rectangle, use clipRect.
alpha of zero is fully transparent, 255 is fully opaque.
Call restoreToCount with returned value to restore this and subsequent saves.
#Param bounds hint to limit the size of Layer; may be nullptr ##
#Param alpha opacity of Layer ##
#Return depth of saved stack ##
#Example
SkPaint paint;
paint.setColor(SK_ColorRED);
canvas->drawCircle(50, 50, 50, paint);
canvas->saveLayerAlpha(nullptr, 128);
paint.setColor(SK_ColorBLUE);
canvas->drawCircle(100, 50, 50, paint);
paint.setColor(SK_ColorGREEN);
paint.setAlpha(128);
canvas->drawCircle(75, 90, 50, paint);
canvas->restore();
##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests SaveLayerRec
##
#Enum SaveLayerFlagsSet
#Line # sets SaveLayerRec options ##
#Code
enum SaveLayerFlagsSet {
kPreserveLCDText_SaveLayerFlag = 1 << 1,
kInitWithPrevious_SaveLayerFlag = 1 << 2,
kMaskAgainstCoverage_EXPERIMENTAL_DONT_USE_SaveLayerFlag = 1 << 3,
kDontClipToLayer_Legacy_SaveLayerFlag = kDontClipToLayer_PrivateSaveLayerFlag,
};
typedef uint32_t SaveLayerFlags;
##
#Typedef uint32_t SaveLayerFlags
#Line # options for SaveLayerRec ##
##
SaveLayerFlags provides options that may be used in any combination in SaveLayerRec,
defining how Layer allocated by saveLayer operates. It may be set to zero,
kPreserveLCDText_SaveLayerFlag, kInitWithPrevious_SaveLayerFlag, or both flags.
#Const kPreserveLCDText_SaveLayerFlag 2
#Line # creates Layer for LCD text ##
Creates Layer for LCD text. Flag is ignored if Layer Paint contains
Image_Filter or Color_Filter.
##
#Const kInitWithPrevious_SaveLayerFlag 4
#Line # initializes with previous contents ##
Initializes Layer with the contents of the previous Layer.
##
#Const kMaskAgainstCoverage_EXPERIMENTAL_DONT_USE_SaveLayerFlag 8
#Experimental do not use
##
#Const kDontClipToLayer_Legacy_SaveLayerFlag 0x80000000
#Deprecated soon
##
#Example
#Height 160
#Description
Canvas Layer captures red and blue circles scaled up by four.
scalePaint blends Layer back with transparency.
##
void draw(SkCanvas* canvas) {
SkPaint redPaint, bluePaint, scalePaint;
redPaint.setColor(SK_ColorRED);
canvas->drawCircle(21, 21, 8, redPaint);
bluePaint.setColor(SK_ColorBLUE);
canvas->drawCircle(31, 21, 8, bluePaint);
SkMatrix matrix;
matrix.setScale(4, 4);
scalePaint.setAlpha(0x40);
scalePaint.setImageFilter(
SkImageFilter::MakeMatrixFilter(matrix, kNone_SkFilterQuality, nullptr));
SkCanvas::SaveLayerRec saveLayerRec(nullptr, &scalePaint,
SkCanvas::kInitWithPrevious_SaveLayerFlag);
canvas->saveLayer(saveLayerRec);
canvas->restore();
}
##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha SaveLayerRec
#Enum ##
#Subtopic SaveLayerRec
#Line # contains the state used to create the Layer ##
#Struct SaveLayerRec
#Line # contains the state used to create the Layer ##
#Code
struct SaveLayerRec {
SaveLayerRec*(...
const SkRect* fBounds;
const SkPaint* fPaint;
const SkImageFilter* fBackdrop;
SaveLayerFlags fSaveLayerFlags;
};
##
SaveLayerRec contains the state used to create the Layer.
#Subtopic Overview
#Populate
##
#Subtopic Member
#Populate
##
#Member const SkRect* fBounds
#Line # hints at Layer size limit ##
fBounds is used as a hint to limit the size of Layer; may be nullptr.
fBounds suggests but does not define Layer size. To clip drawing to
a specific rectangle, use clipRect.
##
#Member const SkPaint* fPaint
#Line # modifies overlay ##
fPaint modifies how Layer overlays the prior Layer; may be nullptr.
Color_Alpha, Blend_Mode, Color_Filter, Draw_Looper, Image_Filter, and
Mask_Filter affect Layer draw.
##
#Member const SkImageFilter* fBackdrop
#Line # applies Image_Filter to prior Layer ##
fBackdrop applies Image_Filter to the prior Layer when copying to the Layer;
may be nullptr. Use kInitWithPrevious_SaveLayerFlag to copy the
prior Layer without an Image_Filter.
##
#Member const SkImage* fClipMask
#Line # clips Layer with Mask_Alpha ##
restore() clips Layer by the Color_Alpha channel of fClipMask when
Layer is copied to Device. fClipMask may be nullptr. .
##
#Member const SkMatrix* fClipMatrix
#Line # transforms Mask_Alpha used to clip ##
fClipMatrix transforms fClipMask before it clips Layer. If
fClipMask describes a translucent gradient, it may be scaled and rotated
without introducing artifacts. fClipMatrix may be nullptr.
##
#Member SaveLayerFlags fSaveLayerFlags
#Line # preserves LCD Text, creates with prior Layer contents ##
fSaveLayerFlags are used to create Layer without transparency,
create Layer for LCD text, and to create Layer with the
contents of the previous Layer.
##
#Example
#Height 160
#Description
Canvas Layer captures a red Anti_Aliased circle and a blue Aliased circle scaled
up by four. After drawing another red circle without scaling on top, the Layer is
transferred to the main canvas.
##
void draw(SkCanvas* canvas) {
SkPaint redPaint, bluePaint;
redPaint.setAntiAlias(true);
redPaint.setColor(SK_ColorRED);
canvas->drawCircle(21, 21, 8, redPaint);
bluePaint.setColor(SK_ColorBLUE);
canvas->drawCircle(31, 21, 8, bluePaint);
SkMatrix matrix;
matrix.setScale(4, 4);
auto scaler = SkImageFilter::MakeMatrixFilter(matrix, kNone_SkFilterQuality, nullptr);
SkCanvas::SaveLayerRec saveLayerRec(nullptr, nullptr, scaler.get(), 0);
canvas->saveLayer(saveLayerRec);
canvas->drawCircle(125, 85, 8, redPaint);
canvas->restore();
}
##
#Subtopic Constructor
#Populate
##
#Method SaveLayerRec()
#Line # constructs SaveLayerRec ##
Sets fBounds, fPaint, and fBackdrop to nullptr. Clears fSaveLayerFlags.
#Return empty SaveLayerRec ##
#Example
SkCanvas::SaveLayerRec rec1;
rec1.fSaveLayerFlags = SkCanvas::kPreserveLCDText_SaveLayerFlag;
SkCanvas::SaveLayerRec rec2(nullptr, nullptr, SkCanvas::kPreserveLCDText_SaveLayerFlag);
SkDebugf("rec1 %c= rec2\n", rec1.fBounds == rec2.fBounds
&& rec1.fPaint == rec2.fPaint
&& rec1.fBackdrop == rec2.fBackdrop
&& rec1.fSaveLayerFlags == rec2.fSaveLayerFlags ? '=' : '!');
#StdOut
rec1 == rec2
##
##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha
##
#Method SaveLayerRec(const SkRect* bounds, const SkPaint* paint, SaveLayerFlags saveLayerFlags = 0)
Sets fBounds, fPaint, and fSaveLayerFlags; sets fBackdrop to nullptr.
#Param bounds Layer dimensions; may be nullptr ##
#Param paint applied to Layer when overlaying prior Layer; may be nullptr ##
#Param saveLayerFlags SaveLayerRec options to modify Layer ##
#Return SaveLayerRec with empty backdrop ##
#Example
SkCanvas::SaveLayerRec rec1;
SkCanvas::SaveLayerRec rec2(nullptr, nullptr);
SkDebugf("rec1 %c= rec2\n", rec1.fBounds == rec2.fBounds
&& rec1.fPaint == rec2.fPaint
&& rec1.fBackdrop == rec2.fBackdrop
&& rec1.fSaveLayerFlags == rec2.fSaveLayerFlags ? '=' : '!');
#StdOut
rec1 == rec2
##
##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha
##
#Method SaveLayerRec(const SkRect* bounds, const SkPaint* paint, const SkImageFilter* backdrop,
SaveLayerFlags saveLayerFlags)
Sets fBounds, fPaint, fBackdrop, and fSaveLayerFlags.
#Param bounds Layer dimensions; may be nullptr ##
#Param paint applied to Layer when overlaying prior Layer;
may be nullptr
##
#Param backdrop prior Layer copied with Image_Filter; may be nullptr
##
#Param saveLayerFlags SaveLayerRec options to modify Layer ##
#Return SaveLayerRec fully specified ##
#Example
SkCanvas::SaveLayerRec rec1;
SkCanvas::SaveLayerRec rec2(nullptr, nullptr, nullptr, 0);
SkDebugf("rec1 %c= rec2\n", rec1.fBounds == rec2.fBounds
&& rec1.fPaint == rec2.fPaint
&& rec1.fBackdrop == rec2.fBackdrop
&& rec1.fSaveLayerFlags == rec2.fSaveLayerFlags ? '=' : '!');
#StdOut
rec1 == rec2
##
##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha
##
#Method SaveLayerRec(const SkRect* bounds, const SkPaint* paint, const SkImageFilter* backdrop,
const SkImage* clipMask, const SkMatrix* clipMatrix,
SaveLayerFlags saveLayerFlags)
#Experimental not ready
Sets fBounds, fPaint, fBackdrop, fClipMask, fClipMatrix, and fSaveLayerFlags.
clipMatrix uses Color_Alpha channel of image, transformed by clipMatrix, to clip
Layer when drawn to Canvas.
Implementation is not complete; has no effect if Device is GPU-backed.
#Param bounds Layer dimensions; may be nullptr ##
#Param paint graphics state applied to Layer when overlaying prior
Layer; may be nullptr
##
#Param backdrop prior Layer copied with Image_Filter;
may be nullptr
##
#Param clipMask clip applied to Layer; may be nullptr ##
#Param clipMatrix matrix applied to clipMask; may be nullptr to use
identity matrix
##
#Param saveLayerFlags SaveLayerRec options to modify Layer ##
#Return SaveLayerRec fully specified ##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha
##
#Struct ##
#Subtopic ##
#Method int saveLayer(const SaveLayerRec& layerRec)
#In Layer
Saves Matrix and Clip, and allocates Bitmap for subsequent drawing.
Calling restore() discards changes to Matrix and Clip,
and blends Bitmap with Color_Alpha opacity onto the prior Layer.
Matrix may be changed by translate(), scale(), rotate(), skew(), concat(),
setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect,
clipPath, clipRegion.
SaveLayerRec contains the state used to create the Layer.
Call restoreToCount with returned value to restore this and subsequent saves.
#Param layerRec Layer state ##
#Return depth of save state stack ##
#Example
#Description
The example draws an image, and saves it into a Layer with kInitWithPrevious_SaveLayerFlag.
Next it punches a hole in Layer and restore with SkBlendMode::kPlus.
Where Layer was cleared, the original image will draw unchanged.
Outside of the circle the mandrill is brightened.
##
#Image 3
// sk_sp<SkImage> image = GetResourceAsImage("images/mandrill_256.png");
canvas->drawImage(image, 0, 0, nullptr);
SkCanvas::SaveLayerRec rec;
SkPaint paint;
paint.setBlendMode(SkBlendMode::kPlus);
rec.fSaveLayerFlags = SkCanvas::kInitWithPrevious_SaveLayerFlag;
rec.fPaint = &paint;
canvas->saveLayer(rec);
paint.setBlendMode(SkBlendMode::kClear);
canvas->drawCircle(128, 128, 96, paint);
canvas->restore();
##
#ToDo above example needs to replace GetResourceAsImage with way to select image in fiddle ##
#SeeAlso save() restore() saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha
##
#Subtopic Layer ##
# ------------------------------------------------------------------------------
#Subtopic Matrix
#Line # coordinate transformation ##
#Method void translate(SkScalar dx, SkScalar dy)
#In Matrix
#Line # translates Matrix ##
Translates Matrix by dx along the x-axis and dy along the y-axis.
Mathematically, replaces Matrix with a translation matrix
Premultiplied with Matrix.
This has the effect of moving the drawing by (dx, dy) before transforming
the result with Matrix.
#Param dx distance to translate in x ##
#Param dy distance to translate in y ##
#Example
#Height 128
#Description
scale() followed by translate() produces different results from translate() followed
by scale().
The blue stroke follows translate of (50, 50); a black
fill follows scale of (2, 1/2.f). After restoring the clip, which resets
Matrix, a red frame follows the same scale of (2, 1/2.f); a gray fill
follows translate of (50, 50).
##
void draw(SkCanvas* canvas) {
SkPaint filledPaint;
SkPaint outlinePaint;
outlinePaint.setStyle(SkPaint::kStroke_Style);
outlinePaint.setColor(SK_ColorBLUE);
canvas->save();
canvas->translate(50, 50);
canvas->drawCircle(28, 28, 15, outlinePaint); // blue center: (50+28, 50+28)
canvas->scale(2, 1/2.f);
canvas->drawCircle(28, 28, 15, filledPaint); // black center: (50+(28*2), 50+(28/2))
canvas->restore();
filledPaint.setColor(SK_ColorGRAY);
outlinePaint.setColor(SK_ColorRED);
canvas->scale(2, 1/2.f);
canvas->drawCircle(28, 28, 15, outlinePaint); // red center: (28*2, 28/2)
canvas->translate(50, 50);
canvas->drawCircle(28, 28, 15, filledPaint); // gray center: ((50+28)*2, (50+28)/2)
}
##
#SeeAlso concat() scale() skew() rotate() setMatrix
##
# ------------------------------------------------------------------------------
#Method void scale(SkScalar sx, SkScalar sy)
#In Matrix
#Line # scales Matrix ##
Scales Matrix by sx on the x-axis and sy on the y-axis.
Mathematically, replaces Matrix with a scale matrix
Premultiplied with Matrix.
This has the effect of scaling the drawing by (sx, sy) before transforming
the result with Matrix.
#Param sx amount to scale in x ##
#Param sy amount to scale in y ##
#Example
#Height 160
void draw(SkCanvas* canvas) {
SkPaint paint;
SkRect rect = { 10, 20, 60, 120 };
canvas->translate(20, 20);
canvas->drawRect(rect, paint);
canvas->scale(2, .5f);
paint.setColor(SK_ColorGRAY);
canvas->drawRect(rect, paint);
}
##
#SeeAlso concat() translate() skew() rotate() setMatrix
##
# ------------------------------------------------------------------------------
#Method void rotate(SkScalar degrees)
#In Matrix
#Line # rotates Matrix ##
Rotates Matrix by degrees. Positive degrees rotates clockwise.
Mathematically, replaces Matrix with a rotation matrix
Premultiplied with Matrix.
This has the effect of rotating the drawing by degrees before transforming
the result with Matrix.
#Param degrees amount to rotate, in degrees ##
#Example
#Description
Draw clock hands at time 5:10. The hour hand and minute hand point up and
are rotated clockwise.
##
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
canvas->translate(128, 128);
canvas->drawCircle(0, 0, 60, paint);
canvas->save();
canvas->rotate(10 * 360 / 60); // 10 minutes of 60 scaled to 360 degrees
canvas->drawLine(0, 0, 0, -50, paint);
canvas->restore();
canvas->rotate((5 + 10.f/60) * 360 / 12); // 5 and 10/60 hours of 12 scaled to 360 degrees
canvas->drawLine(0, 0, 0, -30, paint);
}
##
#SeeAlso concat() translate() skew() scale() setMatrix
##
# ------------------------------------------------------------------------------
#Method void rotate(SkScalar degrees, SkScalar px, SkScalar py)
#In Matrix
Rotates Matrix by degrees about a point at (px, py). Positive degrees rotates
clockwise.
Mathematically, constructs a rotation matrix; Premultiplies the rotation matrix by
a translation matrix; then replaces Matrix with the resulting matrix
Premultiplied with Matrix.
This has the effect of rotating the drawing about a given point before
transforming the result with Matrix.
#Param degrees amount to rotate, in degrees ##
#Param px x-axis value of the point to rotate about ##
#Param py y-axis value of the point to rotate about ##
#Example
#Height 192
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setTextSize(96);
canvas->drawString("A1", 130, 100, paint);
canvas->rotate(180, 130, 100);
canvas->drawString("A1", 130, 100, paint);
}
##
#SeeAlso concat() translate() skew() scale() setMatrix
##
# ------------------------------------------------------------------------------
#Method void skew(SkScalar sx, SkScalar sy)
#In Matrix
#Line # skews Matrix ##
Skews Matrix by sx on the x-axis and sy on the y-axis. A positive value of sx
skews the drawing right as y-axis values increase; a positive value of sy skews
the drawing down as x-axis values increase.
Mathematically, replaces Matrix with a skew matrix Premultiplied with Matrix.
This has the effect of skewing the drawing by (sx, sy) before transforming
the result with Matrix.
#Param sx amount to skew on x-axis ##
#Param sy amount to skew on y-axis ##
#Example
#Description
Black text mimics an oblique text style by using a negative skew on x-axis
that shifts the geometry to the right as the y-axis values decrease.
Red text uses a positive skew on y-axis to shift the geometry down
as the x-axis values increase.
Blue text combines sx and sy skew to rotate and scale.
##
SkPaint paint;
paint.setTextSize(128);
canvas->translate(30, 130);
canvas->save();
canvas->skew(-.5, 0);
canvas->drawString("A1", 0, 0, paint);
canvas->restore();
canvas->save();
canvas->skew(0, .5);
paint.setColor(SK_ColorRED);
canvas->drawString("A1", 0, 0, paint);
canvas->restore();
canvas->skew(-.5, .5);
paint.setColor(SK_ColorBLUE);
canvas->drawString("A1", 0, 0, paint);
##
#SeeAlso concat() translate() rotate() scale() setMatrix
##
# ------------------------------------------------------------------------------
#Method void concat(const SkMatrix& matrix)
#In Matrix
#Line # multiplies Matrix by Matrix ##
Replaces Matrix with matrix Premultiplied with existing Matrix.
This has the effect of transforming the drawn geometry by matrix, before
transforming the result with existing Matrix.
#Param matrix matrix to Premultiply with existing Matrix ##
#Example
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setTextSize(80);
paint.setTextScaleX(.3);
SkMatrix matrix;
SkRect rect[2] = {{ 10, 20, 90, 110 }, { 40, 130, 140, 180 }};
matrix.setRectToRect(rect[0], rect[1], SkMatrix::kFill_ScaleToFit);
canvas->drawRect(rect[0], paint);
canvas->drawRect(rect[1], paint);
paint.setColor(SK_ColorWHITE);
canvas->drawString("Here", rect[0].fLeft + 10, rect[0].fBottom - 10, paint);
canvas->concat(matrix);
canvas->drawString("There", rect[0].fLeft + 10, rect[0].fBottom - 10, paint);
}
##
#SeeAlso translate() rotate() scale() skew() setMatrix
##
# ------------------------------------------------------------------------------
#Method void setMatrix(const SkMatrix& matrix)
#In Matrix
#Line # sets Matrix ##
Replaces Matrix with matrix.
Unlike concat(), any prior matrix state is overwritten.
#Param matrix matrix to copy, replacing existing Matrix ##
#Example
#Height 128
void draw(SkCanvas* canvas) {
SkPaint paint;
canvas->scale(4, 6);
canvas->drawString("truth", 2, 10, paint);
SkMatrix matrix;
matrix.setScale(2.8f, 6);
canvas->setMatrix(matrix);
canvas->drawString("consequences", 2, 20, paint);
}
##
#SeeAlso resetMatrix concat() translate() rotate() scale() skew()
##
# ------------------------------------------------------------------------------
#Method void resetMatrix()
#In Matrix
#Line # resets Matrix to identity ##
Sets Matrix to the identity matrix.
Any prior matrix state is overwritten.
#Example
#Height 128
void draw(SkCanvas* canvas) {
SkPaint paint;
canvas->scale(4, 6);
canvas->drawString("truth", 2, 10, paint);
canvas->resetMatrix();
canvas->scale(2.8f, 6);
canvas->drawString("consequences", 2, 20, paint);
}
##
#SeeAlso setMatrix concat() translate() rotate() scale() skew()
##
# ------------------------------------------------------------------------------
#Method const SkMatrix& getTotalMatrix() const
#In Matrix
#Line # returns Matrix ##
Returns Matrix.
This does not account for translation by Device or Surface.
#Return Matrix in Canvas ##
#Example
SkDebugf("isIdentity %s\n", canvas->getTotalMatrix().isIdentity() ? "true" : "false");
#StdOut
isIdentity true
##
##
#SeeAlso setMatrix resetMatrix concat()
##
#Subtopic Matrix ##
# ------------------------------------------------------------------------------
#Subtopic Clip
#Line # stack of clipping Paths ##
Clip is built from a stack of clipping paths. Each Path in the
stack can be constructed from one or more Path_Contour elements. The
Path_Contour may be composed of any number of Path_Verb segments. Each
Path_Contour forms a closed area; Path_Fill_Type defines the area enclosed
by Path_Contour.
Clip stack of Path elements successfully restrict the Path area. Each
Path is transformed by Matrix, then intersected with or subtracted from the
prior Clip to form the replacement Clip. Use SkClipOp::kDifference
to subtract Path from Clip; use SkClipOp::kIntersect to intersect Path
with Clip.
A clipping Path may be Anti_Aliased; if Path, after transformation, is
composed of horizontal and vertical lines, clearing Anti_Alias allows whole pixels
to either be inside or outside the clip. The fastest drawing has a Aliased,
rectangular clip.
If clipping Path has Anti_Alias set, clip may partially clip a pixel, requiring
that drawing blend partially with the destination along the edge. A rotated
rectangular Anti_Aliased clip looks smoother but draws slower.
Clip can combine with Rect and Round_Rect primitives; like
Path, these are transformed by Matrix before they are combined with Clip.
Clip can combine with Region. Region is assumed to be in Device coordinates
and is unaffected by Matrix.
#Example
#Height 90
#Description
Draw a red circle with an Aliased clip and an Anti_Aliased clip.
Use an image filter to zoom into the pixels drawn.
The edge of the Aliased clip fully draws pixels in the red circle.
The edge of the Anti_Aliased clip partially draws pixels in the red circle.
##
SkPaint redPaint, scalePaint;
redPaint.setAntiAlias(true);
redPaint.setColor(SK_ColorRED);
canvas->save();
for (bool antialias : { false, true } ) {
canvas->save();
canvas->clipRect(SkRect::MakeWH(19.5f, 11.5f), antialias);
canvas->drawCircle(17, 11, 8, redPaint);
canvas->restore();
canvas->translate(16, 0);
}
canvas->restore();
SkMatrix matrix;
matrix.setScale(6, 6);
scalePaint.setImageFilter(
SkImageFilter::MakeMatrixFilter(matrix, kNone_SkFilterQuality, nullptr));
SkCanvas::SaveLayerRec saveLayerRec(
nullptr, &scalePaint, SkCanvas::kInitWithPrevious_SaveLayerFlag);
canvas->saveLayer(saveLayerRec);
canvas->restore();
##
#Method void clipRect(const SkRect& rect, SkClipOp op, bool doAntiAlias)
#In Clip
#Line # combines Clip with Rect ##
Replaces Clip with the intersection or difference of Clip and rect,
with an Aliased or Anti_Aliased clip edge. rect is transformed by Matrix
before it is combined with Clip.
#Param rect Rect to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Param doAntiAlias true if Clip is to be Anti_Aliased ##
#Example
#Height 128
void draw(SkCanvas* canvas) {
canvas->rotate(10);
SkPaint paint;
paint.setAntiAlias(true);
for (auto alias: { false, true } ) {
canvas->save();
canvas->clipRect(SkRect::MakeWH(90, 80), SkClipOp::kIntersect, alias);
canvas->drawCircle(100, 60, 60, paint);
canvas->restore();
canvas->translate(80, 0);
}
}
##
#SeeAlso clipRRect clipPath clipRegion
##
#Method void clipRect(const SkRect& rect, SkClipOp op)
#In Clip
Replaces Clip with the intersection or difference of Clip and rect.
Resulting Clip is Aliased; pixels are fully contained by the clip.
rect is transformed by Matrix before it is combined with Clip.
#Param rect Rect to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Example
#Height 192
#Width 280
void draw(SkCanvas* canvas) {
SkPaint paint;
for (SkClipOp op: { SkClipOp::kIntersect, SkClipOp::kDifference } ) {
canvas->save();
canvas->clipRect(SkRect::MakeWH(90, 120), op, false);
canvas->drawCircle(100, 100, 60, paint);
canvas->restore();
canvas->translate(80, 0);
}
}
##
#SeeAlso clipRRect clipPath clipRegion
##
#Method void clipRect(const SkRect& rect, bool doAntiAlias = false)
#In Clip
Replaces Clip with the intersection of Clip and rect.
Resulting Clip is Aliased; pixels are fully contained by the clip.
rect is transformed by Matrix
before it is combined with Clip.
#Param rect Rect to combine with Clip ##
#Param doAntiAlias true if Clip is to be Anti_Aliased ##
#Example
#Height 133
#Description
A circle drawn in pieces looks uniform when drawn Aliased.
The same circle pieces blend with pixels more than once when Anti_Aliased,
visible as a thin pair of lines through the right circle.
##
void draw(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(0x8055aaff);
SkRect clipRect = { 0, 0, 87.4f, 87.4f };
for (auto alias: { false, true } ) {
canvas->save();
canvas->clipRect(clipRect, SkClipOp::kIntersect, alias);
canvas->drawCircle(67, 67, 60, paint);
canvas->restore();
canvas->save();
canvas->clipRect(clipRect, SkClipOp::kDifference, alias);
canvas->drawCircle(67, 67, 60, paint);
canvas->restore();
canvas->translate(120, 0);
}
}
##
#SeeAlso clipRRect clipPath clipRegion
##
#Method void androidFramework_setDeviceClipRestriction(const SkIRect& rect)
#In Clip
#Line # exists for use by Android framework ##
Sets the maximum clip rectangle, which can be set by clipRect, clipRRect and
clipPath and intersect the current clip with the specified rect.
The maximum clip affects only future clipping operations; it is not retroactive.
The clip restriction is not recorded in pictures.
Pass an empty rect to disable maximum clip.
#Private
This private API is for use by Android framework only.
##
#Param rect maximum allowed clip in device coordinates
#Param ##
##
#Method void clipRRect(const SkRRect& rrect, SkClipOp op, bool doAntiAlias)
#In Clip
#Line # combines Clip with Round_Rect ##
Replaces Clip with the intersection or difference of Clip and rrect,
with an Aliased or Anti_Aliased clip edge.
rrect is transformed by Matrix
before it is combined with Clip.
#Param rrect Round_Rect to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Param doAntiAlias true if Clip is to be Anti_Aliased ##
#Example
#Height 128
void draw(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
SkPaint paint;
paint.setAntiAlias(true);
paint.setColor(0x8055aaff);
SkRRect oval;
oval.setOval({10, 20, 90, 100});
canvas->clipRRect(oval, SkClipOp::kIntersect, true);
canvas->drawCircle(70, 100, 60, paint);
}
##
#SeeAlso clipRect clipPath clipRegion
##
#Method void clipRRect(const SkRRect& rrect, SkClipOp op)
#In Clip
Replaces Clip with the intersection or difference of Clip and rrect.
Resulting Clip is Aliased; pixels are fully contained by the clip.
rrect is transformed by Matrix before it is combined with Clip.
#Param rrect Round_Rect to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Example
#Height 128
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setColor(0x8055aaff);
auto oval = SkRRect::MakeOval({10, 20, 90, 100});
canvas->clipRRect(oval, SkClipOp::kIntersect);
canvas->drawCircle(70, 100, 60, paint);
}
##
#SeeAlso clipRect clipPath clipRegion
##
#Method void clipRRect(const SkRRect& rrect, bool doAntiAlias = false)
#In Clip
Replaces Clip with the intersection of Clip and rrect,
with an Aliased or Anti_Aliased clip edge.
rrect is transformed by Matrix before it is combined with Clip.
#Param rrect Round_Rect to combine with Clip ##
#Param doAntiAlias true if Clip is to be Anti_Aliased ##
#Example
#Height 128
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
auto oval = SkRRect::MakeRectXY({10, 20, 90, 100}, 9, 13);
canvas->clipRRect(oval, true);
canvas->drawCircle(70, 100, 60, paint);
}
##
#SeeAlso clipRect clipPath clipRegion
##
#Method void clipPath(const SkPath& path, SkClipOp op, bool doAntiAlias)
#In Clip
#Line # combines Clip with Path ##
Replaces Clip with the intersection or difference of Clip and path,
with an Aliased or Anti_Aliased clip edge. Path_Fill_Type determines if path
describes the area inside or outside its contours; and if Path_Contour overlaps
itself or another Path_Contour, whether the overlaps form part of the area.
path is transformed by Matrix before it is combined with Clip.
#Param path Path to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Param doAntiAlias true if Clip is to be Anti_Aliased ##
#Example
#Description
Top figure uses SkPath::kInverseWinding_FillType and SkClipOp::kDifference;
area outside clip is subtracted from circle.
Bottom figure uses SkPath::kWinding_FillType and SkClipOp::kIntersect;
area inside clip is intersected with circle.
##
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
SkPath path;
path.addRect({20, 30, 100, 110});
path.setFillType(SkPath::kInverseWinding_FillType);
canvas->save();
canvas->clipPath(path, SkClipOp::kDifference, false);
canvas->drawCircle(70, 100, 60, paint);
canvas->restore();
canvas->translate(100, 100);
path.setFillType(SkPath::kWinding_FillType);
canvas->clipPath(path, SkClipOp::kIntersect, false);
canvas->drawCircle(70, 100, 60, paint);
}
##
#SeeAlso clipRect clipRRect clipRegion
##
#Method void clipPath(const SkPath& path, SkClipOp op)
#In Clip
Replaces Clip with the intersection or difference of Clip and path.
Resulting Clip is Aliased; pixels are fully contained by the clip.
Path_Fill_Type determines if path
describes the area inside or outside its contours; and if Path_Contour overlaps
itself or another Path_Contour, whether the overlaps form part of the area.
path is transformed by Matrix
before it is combined with Clip.
#Param path Path to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Example
#Description
Overlapping Rects form a clip. When clip Path_Fill_Type is set to
SkPath::kWinding_FillType, the overlap is included. Set to
SkPath::kEvenOdd_FillType, the overlap is excluded and forms a hole.
##
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
SkPath path;
path.addRect({20, 15, 100, 95});
path.addRect({50, 65, 130, 135});
path.setFillType(SkPath::kWinding_FillType);
canvas->save();
canvas->clipPath(path, SkClipOp::kIntersect);
canvas->drawCircle(70, 85, 60, paint);
canvas->restore();
canvas->translate(100, 100);
path.setFillType(SkPath::kEvenOdd_FillType);
canvas->clipPath(path, SkClipOp::kIntersect);
canvas->drawCircle(70, 85, 60, paint);
}
##
#SeeAlso clipRect clipRRect clipRegion
##
#Method void clipPath(const SkPath& path, bool doAntiAlias = false)
#In Clip
Replaces Clip with the intersection of Clip and path.
Resulting Clip is Aliased; pixels are fully contained by the clip.
Path_Fill_Type determines if path
describes the area inside or outside its contours; and if Path_Contour overlaps
itself or another Path_Contour, whether the overlaps form part of the area.
path is transformed by Matrix before it is combined with Clip.
#Param path Path to combine with Clip ##
#Param doAntiAlias true if Clip is to be Anti_Aliased ##
#Example
#Height 212
#Description
Clip loops over itself covering its center twice. When clip Path_Fill_Type
is set to SkPath::kWinding_FillType, the overlap is included. Set to
SkPath::kEvenOdd_FillType, the overlap is excluded and forms a hole.
##
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
SkPath path;
SkPoint poly[] = {{20, 20}, { 80, 20}, { 80, 80}, {40, 80},
{40, 40}, {100, 40}, {100, 100}, {20, 100}};
path.addPoly(poly, SK_ARRAY_COUNT(poly), true);
path.setFillType(SkPath::kWinding_FillType);
canvas->save();
canvas->clipPath(path, SkClipOp::kIntersect);
canvas->drawCircle(50, 50, 45, paint);
canvas->restore();
canvas->translate(100, 100);
path.setFillType(SkPath::kEvenOdd_FillType);
canvas->clipPath(path, SkClipOp::kIntersect);
canvas->drawCircle(50, 50, 45, paint);
}
##
#SeeAlso clipRect clipRRect clipRegion
##
# ------------------------------------------------------------------------------
#Method void setAllowSimplifyClip(bool allow)
#In Clip
#Experimental testing
Set to simplify clip stack using PathOps.
##
# ------------------------------------------------------------------------------
#Method void clipRegion(const SkRegion& deviceRgn, SkClipOp op = SkClipOp::kIntersect)
#In Clip
#Line # combines Clip with Region ##
Replaces Clip with the intersection or difference of Clip and Region deviceRgn.
Resulting Clip is Aliased; pixels are fully contained by the clip.
deviceRgn is unaffected by Matrix.
#Param deviceRgn Region to combine with Clip ##
#Param op Clip_Op to apply to Clip ##
#Example
#Description
region is unaffected by canvas rotation; iRect is affected by canvas rotation.
Both clips are Aliased; this is not noticeable on Region clip because it
aligns to pixel boundaries.
##
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
SkIRect iRect = {30, 40, 120, 130 };
SkRegion region(iRect);
canvas->rotate(10);
canvas->save();
canvas->clipRegion(region, SkClipOp::kIntersect);
canvas->drawCircle(50, 50, 45, paint);
canvas->restore();
canvas->translate(100, 100);
canvas->clipRect(SkRect::Make(iRect), SkClipOp::kIntersect);
canvas->drawCircle(50, 50, 45, paint);
}
##
#SeeAlso clipRect clipRRect clipPath
##
#Method bool quickReject(const SkRect& rect) const
#In Clip
#Line # returns if Rect is outside Clip ##
Returns true if Rect rect, transformed by Matrix, can be quickly determined to be
outside of Clip. May return false even though rect is outside of Clip.
Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
#Param rect Rect to compare with Clip ##
#Return true if rect, transformed by Matrix, does not intersect Clip ##
#Example
void draw(SkCanvas* canvas) {
SkRect testRect = {30, 30, 120, 129 };
SkRect clipRect = {30, 130, 120, 230 };
canvas->save();
canvas->clipRect(clipRect);
SkDebugf("quickReject %s\n", canvas->quickReject(testRect) ? "true" : "false");
canvas->restore();
canvas->rotate(10);
canvas->clipRect(clipRect);
SkDebugf("quickReject %s\n", canvas->quickReject(testRect) ? "true" : "false");
}
#StdOut
quickReject true
quickReject false
##
##
#SeeAlso getLocalClipBounds getTotalMatrix SkBitmap::drawsNothing
##
#Method bool quickReject(const SkPath& path) const
#In Clip
Returns true if path, transformed by Matrix, can be quickly determined to be
outside of Clip. May return false even though path is outside of Clip.
Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
#Param path Path to compare with Clip ##