Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 11): A Real Stroke Engine
Contents
- Introduction
- The one design decision
- Caps and joins
- The stroker
- Dashes
- The context learns to stroke
- The demo
- Project structure
- The library can draw a line
Introduction
Our graphics library can fill arbitrary paths, but it still lacks a proper stroke operation. This limitation becomes apparent even when drawing a simple panel border: instead of outlining a rectangle directly, we have to construct its border from four separate filled rectangles.
The workaround looks like this:
//--- a 1 px border as four thin rectangles. Part 10 has no stroker //--- yet; that is the next part, and this is the honest stand-in. g_ctx.SetSourceColor(C_LINE); g_ctx.Rect(x, y, w, 1.0); g_ctx.Rect(x, y + h - 1, w, 1.0); g_ctx.Rect(x, y, 1.0, h); g_ctx.Rect(x + w - 1, y, 1.0, h); g_ctx.Fill();
Using four thin rectangles, as demonstrated in Part 10, works for drawing the border of an axis-aligned rectangle with integer dimensions, but it is only a limited workaround. It cannot properly handle rounded rectangles, rotated shapes, diagonal lines, or more complex paths such as price series. What should be a basic drawing operation becomes a collection of special cases.
At this stage of development, the library can fill almost any outline it can describe, but it still lacks a proper stroke operation. In Part 5, we constructed a thick line segment using two triangles, explicitly treating it as a building block rather than a complete stroking system. This article addresses that limitation by introducing a dedicated stroker that can draw lines along any path supported by the library.
The new stroke system provides control over line width, three types of end caps, three types of corner joins, miter limits, and dash patterns. These features make it possible to render everything from simple borders and straight lines to complex paths with consistent stroke behavior.
The implementation introduces one new file, Stroke.mqh. Existing components remain unchanged, except for Context.mqh, which gains the stroke settings and two methods used to configure and execute the new rendering operation.
Color.mqh Part 1, 4 the ARGB color type, compositing
Config.mqh Part 4, 6 the two quality dials
Surface.mqh Part 1 a pixel buffer bound to one chart object
Matrix.mqh Part 10 the six-number transform
Path.mqh Parts 2-10 the geometry layer
Paint.mqh Part 8 the color source, and the two gradients
Clip.mqh Part 9 where drawing is allowed to land
Raster.mqh Parts 3-9 the scanline fill
Stroke.mqh Part 11 the outline of a line <- new today
Context.mqh Part 10 the object an application talks to
Part 11 + line settings, Stroke <- changed
The one design decision
A stroker can be written two ways, and the choice decides how hard the rest of the file is.
It can offset the outline: walk the path, push every point sideways by half the line width to get the left edge, do the same on the other side, reverse the second and join the two into a single closed loop. This produces the smallest outline possible — one contour, no overlaps. It also requires detecting and resolving every place where the offset curve crosses itself, which happens whenever the path turns more sharply than the line width allows. That is where most stroking bugs in most graphics libraries live.
Or it can emit a pile of overlapping pieces: a quad for every segment, a wedge for every bend, a shape for every open end — and let the fill rule weld them together.

This file takes the second route, and the reason is Part 5. The non-zero winding rule counts how many times the boundary wraps around a point, and a point covered by three overlapping pieces has a winding number of 3, which is not zero, which means filled. Overlaps are not a problem to be solved — under non-zero they are the mechanism.
Three consequences, all good:
- It needs no self-intersection code at all, because self-intersection is the expected input rather than an edge case. That is one class of bug removed and not all of them — the pieces still have to be wound consistently and the degenerate ones still have to be dropped, which is what EmitPolygon does below.
- It needs no new code in the inner loop. The rasterizer from Parts 3 to 9 fills the result exactly as it fills anything else.
- It is the natural extension of what Part 5 already demonstrated with two quads and a joint polygon.
The cost is more edges than an offset outline would produce. A dashed, round-joined 300-point polyline is a few thousand edges rather than a few hundred. That cost is real, it is paid in the scanline sweep, and a later part in this series is about making that sweep cheap.
One rule follows from the design and the caller has to respect it:
Fill a stroke outline with CAIRO_NONZERO. Under the even-odd rule, every region that the pieces cover an even number of times drops back out — the inside of every bend, where two quads overlap, and the whole of a disc that sits on top of one — and the stroke comes out as lace.
Caps and joins
enum ENUM_CAIRO_CAP { CAIRO_CAP_BUTT = 0, CAIRO_CAP_ROUND = 1, CAIRO_CAP_SQUARE = 2 }; enum ENUM_CAIRO_JOIN { CAIRO_JOIN_MITER = 0, CAIRO_JOIN_ROUND = 1, CAIRO_JOIN_BEVEL = 2 };

A cap is what happens at the end of an open contour. BUTT stops exactly at the last point, and it is the only one of the three that keeps a line's length exactly as drawn — which is why it is the default and why a measured chart line should use it. ROUND adds a half disc; it is what a pen nib does and what a data line usually wants. SQUARE adds half a line width of straight line, used where two separately drawn strokes have to appear to meet.
A join fills the notch at a bend. Two quads meeting at an angle cover the inside of the bend twice — which the non-zero rule handles for free — and leave a wedge-shaped gap on the outside. MITER extends both outer edges until they meet, which is sharp and is the default. ROUND puts a disc at the vertex, never spikes, and is the right answer for data lines where a sharp tick should not grow a needle. BEVEL cuts the notch off straight, is the cheapest, and is what a miter falls back to when it runs past its limit.
The stroker
//+-------------------------------------------------------------------+ //| Stroke.mqh | //+-------------------------------------------------------------------+ #ifndef CAIRO5_STROKE_MQH #define CAIRO5_STROKE_MQH #include "Config.mqh" #include "Path.mqh" //--- a segment shorter than this has no reliable direction, so it has //--- no normal either and is skipped #define CAIRO_STROKE_EPSILON 1e-9 //+-------------------------------------------------------------------+ //| ENUM_CAIRO_CAP - how an OPEN contour ends. | //+-------------------------------------------------------------------+ enum ENUM_CAIRO_CAP { CAIRO_CAP_BUTT = 0, CAIRO_CAP_ROUND = 1, CAIRO_CAP_SQUARE = 2 }; //+-------------------------------------------------------------------+ //| ENUM_CAIRO_JOIN - what fills the wedge at a bend. | //+-------------------------------------------------------------------+ enum ENUM_CAIRO_JOIN { CAIRO_JOIN_MITER = 0, CAIRO_JOIN_ROUND = 1, CAIRO_JOIN_BEVEL = 2 }; //+-------------------------------------------------------------------+ //| CCairoStroker | //+-------------------------------------------------------------------+ class CCairoStroker { private: double m_width; ENUM_CAIRO_CAP m_cap; ENUM_CAIRO_JOIN m_join; double m_miter_limit; //--- the dash pattern: on, off, on, off ... in pixels double m_dashes[]; int m_dash_count; double m_dash_offset; //--- scratch for one contour, and for one dash segment of it double m_cx[]; double m_cy[]; int m_cn; double m_dx[]; double m_dy[]; int m_dn;Keep one and reuse it. The dash pattern and both scratch buffers survive between calls, so stroking two hundred lines in a frame allocates nothing after the first few calls — like CCairoPath and CCairoRasterizer. Two costs remain: (1) EmitDisc allocates local arrays for each round cap and round join (twice per vertex for round joins), and (2) the output path grows as pieces are appended until its capacity stabilizes.
The public operation is a single method:
//--- THE ONE PUBLIC OPERATION. `out` is cleared first, and is //--- filled with CAIRO_NONZERO by the caller. bool Stroke(CCairoPath &src, CCairoPath &out);
Strokereads one path and writes another. The output is ordinary geometry — contours of straight segments — so it can be filled, clipped, hit-tested with Part 9's Contains, measured with Bounds, or appended to another path like anything else the library produces. The demo takes advantage of exactly that to show the pieces.
The piecesEvery piece is one closed contour, and every one of them is wound the same way, so the non-zero rule welds rather than cancels them. That is not an invariant the constructions below are trusted to respect. EmitPolygon measures twice the signed area by the shoelace formula, emits the vertices in reverse order when it comes out negative, and drops the piece when it comes out zero. Three multiplications per piece buy the guarantee for the quad, the miter, the bevel and the disc alike, which is what makes the sentence above true of the join fallback and of every dash fragment too. A segment is the simplest:
//+-------------------------------------------------------------------+ //| One segment of the stroke, as a rectangle. | //+-------------------------------------------------------------------+ void CCairoStroker::EmitSegment(CCairoPath &out, const double x0, const double y0, const double x1, const double y1) { const double dx = x1 - x0; const double dy = y1 - y0; const double len = MathSqrt(dx * dx + dy * dy); if(!(len > CAIRO_STROKE_EPSILON)) return; const double h = m_width * 0.5; const double nx = -dy / len * h; const double ny = dx / len * h; double xs[4], ys[4]; xs[0] = x0 + nx; ys[0] = y0 + ny; xs[1] = x0 - nx; ys[1] = y0 - ny; xs[2] = x1 - nx; ys[2] = y1 - ny; xs[3] = x1 + nx; ys[3] = y1 + ny; EmitPolygon(out, xs, ys, 4); }
(-dy, dx) is the segment direction rotated a quarter turn — the normal. Scaled to half the line width it gives the offset from the center line to either edge, and the four corners follow. The length test is not a micro-optimization: a zero-length segment has no direction, so it has no normal, and every piece in this file is built from a normal. CAIRO_STROKE_EPSILON is 1e-9, and the test is written as !(len > eps) rather than len <= eps so that a NaN arriving from bad input reads as "skip" rather than as "proceed".
The join, and where the outside of a bend is
//+-------------------------------------------------------------------+ //| The join at an interior vertex. | //+-------------------------------------------------------------------+ void CCairoStroker::EmitJoin(CCairoPath &out, const double px, const double py, const double vx, const double vy, const double nx, const double ny) { if(m_join == CAIRO_JOIN_ROUND) { EmitDisc(out, px, py); return; } const double h = m_width * 0.5; //--- the normals of the two segments, pointing to the same side const double n1x = -vy * h, n1y = vx * h; const double n2x = -ny * h, n2y = nx * h; //--- which side is the outside of the bend? The cross product of //--- the two directions says which way the path turned. const double cross = vx * ny - vy * nx; if(MathAbs(cross) < CAIRO_STROKE_EPSILON) return; // straight ahead, or a full reversal const double sign = (cross > 0.0) ? -1.0 : 1.0; //--- the two outer corners const double ax = px + n1x * sign, ay = py + n1y * sign; const double bx = px + n2x * sign, by = py + n2y * sign;
The round join is the easy one — a disc at the vertex covers the notch whatever the angle, so it returns immediately.
For the other two the code has to know which side the notch is on, and the cross product of the two unit directions answers it: positive means the path turned one way, negative the other. When it is near zero the path went straight ahead, or reversed exactly. Straight ahead leaves no notch. A reversal deserves checking rather than asserting: the two normals are then opposite, the two outer corners sit symmetrically about the vertex, and the triangle through them is collinear and encloses no area — so EmitPolygon would reject it even if it were emitted, and the miter that would otherwise be extended runs to infinity and loses to any limit. Returning early draws the same picture, sooner. A reversal under ROUND still gets its disc, because that branch returned before this test.
The miter is the only piece with real arithmetic in it:
if(m_join == CAIRO_JOIN_MITER) { //--- the miter point lies along the bisector of the two //--- normals, at 1 / cos(theta/2) times the half width double mx = ax + bx - 2.0 * px; double my = ay + by - 2.0 * py; const double mlen = MathSqrt(mx * mx + my * my); if(mlen > CAIRO_STROKE_EPSILON) { mx /= mlen; my /= mlen; //--- cos of half the angle between the two normals const double cos_half = ((ax - px) * mx + (ay - py) * my) / h; if(cos_half > CAIRO_STROKE_EPSILON) { const double miter_len = h / cos_half; //--- the limit is expressed against the full width, //--- which is how every other library states it if(miter_len / h <= m_miter_limit) { double xs[4], ys[4]; xs[0] = px; ys[0] = py; xs[1] = ax; ys[1] = ay; xs[2] = px + mx * miter_len; ys[2] = py + my * miter_len; xs[3] = bx; ys[3] = by; EmitPolygon(out, xs, ys, 4); return; } } } }
The sum of the two outer corner offsets points along the bisector of the bend. Normalized, it is the direction the spike runs in; cos_half is the cosine of half the angle between the two normals, and h / cos_half is how far along that direction the two outer edges actually meet.
Why there is a limit at all
As the bend gets sharper, cos_half goes to zero and miter_len goes to infinity. The number compared against the limit is miter_len / h, which works out as 1 / sin(theta / 2) for a turn of theta between the two segments. At 120 degrees it is 1.15 and nobody notices. At 60 degrees it is 2.00. At 20 degrees it is 5.76, and at 2 degrees it is 57 — a spike most of the way across the panel, produced by a path that merely doubled back on itself.
So the stroker compares the spike against the limit and falls through to the bevel when it loses:
//--- BEVEL, and the fallback for a miter that ran past its limit double tx[3], ty[3]; tx[0] = px; ty[0] = py; tx[1] = ax; ty[1] = ay; tx[2] = bx; ty[2] = by; EmitPolygon(out, tx, ty, 3); }
That comparison divides by h, not by the full width. This matters because using 'spike length over line width' would be off by a factor of two. miter_len is the distance from the vertex out to the tip, which is half of what SVG and PostScript call the miter length — those two measure the whole diagonal, from the inner corner of the join through the vertex to the tip. Half of that length divided by h equals the full length divided by the full width. Therefore this code enforces the same ratio as SVG and PostScript, and a value copied from a design tool preserves its meaning. The default is 10, which lets everything down to about 11 degrees through; SVG's default of 4 would cut off at about 29 degrees, which is the figure its own specification quotes, and the check worth doing on an arithmetic like this one.
Walking a contour
//+-------------------------------------------------------------------+ //| Stroke the polyline currently in the scratch buffer. | //+-------------------------------------------------------------------+ void CCairoStroker::StrokeScratch(CCairoPath &out, const bool closed) { if(m_cn <= 0) return; //--- a contour that collapsed to a single point still draws a dot //--- under a round cap, which is what a zero-length data point //--- with round ends should look like if(m_cn == 1) { if(m_cap == CAIRO_CAP_ROUND) EmitDisc(out, m_cx[0], m_cy[0]); return; } const int last = m_cn - 1; //--- every segment becomes a rectangle for(int i = 0; i < last; i++) EmitSegment(out, m_cx[i], m_cy[i], m_cx[i + 1], m_cy[i + 1]); if(closed) EmitSegment(out, m_cx[last], m_cy[last], m_cx[0], m_cy[0]); //--- every interior vertex becomes a join for(int i = 1; i < last; i++) { double v1x = m_cx[i] - m_cx[i - 1]; double v1y = m_cy[i] - m_cy[i - 1]; double v2x = m_cx[i + 1] - m_cx[i]; double v2y = m_cy[i + 1] - m_cy[i]; const double l1 = MathSqrt(v1x * v1x + v1y * v1y); const double l2 = MathSqrt(v2x * v2x + v2y * v2y); if(!(l1 > CAIRO_STROKE_EPSILON) || !(l2 > CAIRO_STROKE_EPSILON)) continue; EmitJoin(out, m_cx[i], m_cy[i], v1x / l1, v1y / l1, v2x / l2, v2y / l2); }
Segments, then joins, then — for an open contour — a cap at each end. A closed contour of two or more points gets no caps at all; instead the first and last vertices, which an open contour would have capped, are interior vertices and get joins:
if(closed) { //--- the two vertices an open contour would have capped are //--- interior vertices of a closed one, so they get joins double v1x = m_cx[0] - m_cx[last]; double v1y = m_cy[0] - m_cy[last]; double v2x = m_cx[1] - m_cx[0]; double v2y = m_cy[1] - m_cy[0]; double l1 = MathSqrt(v1x * v1x + v1y * v1y); double l2 = MathSqrt(v2x * v2x + v2y * v2y); if(l1 > CAIRO_STROKE_EPSILON && l2 > CAIRO_STROKE_EPSILON) EmitJoin(out, m_cx[0], m_cy[0], v1x / l1, v1y / l1, v2x / l2, v2y / l2); v1x = m_cx[last] - m_cx[last - 1]; v1y = m_cy[last] - m_cy[last - 1]; v2x = m_cx[0] - m_cx[last]; v2y = m_cy[0] - m_cy[last]; l1 = MathSqrt(v1x * v1x + v1y * v1y); l2 = MathSqrt(v2x * v2x + v2y * v2y); if(l1 > CAIRO_STROKE_EPSILON && l2 > CAIRO_STROKE_EPSILON) EmitJoin(out, m_cx[last], m_cy[last], v1x / l1, v1y / l1, v2x / l2, v2y / l2); return; } //--- an open contour gets a cap at each end, pointing outward double sx = m_cx[0] - m_cx[1]; double sy = m_cy[0] - m_cy[1]; double sl = MathSqrt(sx * sx + sy * sy); if(sl > CAIRO_STROKE_EPSILON) EmitCap(out, m_cx[0], m_cy[0], sx / sl, sy / sl); double ex = m_cx[last] - m_cx[last - 1]; double ey = m_cy[last] - m_cy[last - 1]; double el = MathSqrt(ex * ex + ey * ey); if(el > CAIRO_STROKE_EPSILON) EmitCap(out, m_cx[last], m_cy[last], ex / el, ey / el); }
One case is handled before any of that, and it is the kind of thing a library is judged on:
//--- a contour that collapsed to a single point still draws a dot //--- under a round cap, which is what a zero-length data point //--- with round ends should look like if(m_cn == 1) { if(m_cap == CAIRO_CAP_ROUND) EmitDisc(out, m_cx[0], m_cy[0]); return; }
A single-point contour with round caps is a dot. With butt caps it is nothing, which is right for a butt cap: it adds no geometry, and a line of zero length with nothing added to it encloses no area. With a square cap it is also nothing here, and that is a simplification rather than a derivation — Cairo and SVG both paint a square of one full line width in this case, since a square cap extends half a width past each end and here the two ends coincide. The test above asks only about ROUND, so a square cap never reaches EmitCap. The test also runs before the open-or-closed decision, which means a one-point contour is treated as open whatever its close flag says — so a closed contour that collapsed to a point does get a disc under ROUND, and the rule about closed contours never being capped is a rule about contours that have a length.
The cap, and why one function serves both ends
//+-------------------------------------------------------------------+ //| The cap at the end of an open contour. | //+-------------------------------------------------------------------+ void CCairoStroker::EmitCap(CCairoPath &out, const double px, const double py, const double dx, const double dy) { if(m_cap == CAIRO_CAP_BUTT) return; if(m_cap == CAIRO_CAP_ROUND) { //--- a full disc rather than a half one. The half that laps //--- back over the line is already covered by the segment //--- quad, and under the non-zero rule covering a region //--- twice is exactly the same as covering it once. EmitDisc(out, px, py); return; } //--- SQUARE: half a line width of extra straight line const double h = m_width * 0.5; const double nx = -dy * h, ny = dx * h; const double ex = dx * h, ey = dy * h; double xs[4], ys[4]; xs[0] = px + nx; ys[0] = py + ny; xs[1] = px + nx + ex; ys[1] = py + ny + ey; xs[2] = px - nx + ex; ys[2] = py - ny + ey; xs[3] = px - nx; ys[3] = py - ny; EmitPolygon(out, xs, ys, 4); }
The caller passes a direction that already points away from the line, which it computes by subtracting the second point from the first at the start and the second-to-last from the last at the end. Everything inside the function is then written once: a round cap is a disc at p, a square cap is a rectangle half a width long in direction d, and a butt cap is nothing at all.
That is a small thing, and it is the difference between a file with two cap functions that drift apart over time and a file with one. It is an argument about maintenance and not about correctness: one function cannot be right at one end and wrong at the other, but it can be wrong at both. What settles whether it is right are the degenerate cases — the zero-length segment that has no direction to pass it, and the single-point contour above.
What the stroker never sees
Three things are already settled by the time a path reaches it, and each one is a feature it did not have to implement.
Curves.CCairoPath flattens every Bézier and every arc as it is built, back in Parts 6 and 7, so by the time the stroker walks a contour there are no curves left — only straight segments between stored vertices. Stroking a circle and stroking a 37-sided polygon are the same operation, and the only reason the circle looks round is that Part 7 chose 37 sides for its radius.
The transform. Every vertex was pushed through the current matrix in Part 10's AddPoint, so the geometry arrives in device pixels. The stroker has no idea a transform exists; the context converts the width for it, and that is the entire interaction — under one condition on the caller, named where the conversion happens.
Which contours are closed. Part 5 made Close() record a flag per contour rather than appending a duplicate vertex, and Stroke() reads that flag to decide between caps and joins at the two ends. A closed contour that stored its first point twice would be indistinguishable from an open one that happened to return home — and it would also grow a stray join on a straight line.
Each of those was a decision made for its own reasons, several parts ago, and each one pays off here. That is the argument for building a library in this order rather than writing the stroker first and discovering what it needs.
Round caps and joins need a circle
//+-------------------------------------------------------------------+ //| How many segments a disc of this radius needs. | //+-------------------------------------------------------------------+ int CCairoStroker::ArcSteps(const double radius) const { if(!(radius > 0.0)) return 8; double ratio = CairoFlattenTolerance / radius; if(ratio > 1.0) ratio = 1.0; const double step = 2.0 * MathArccos(1.0 - ratio); if(!(step > 1e-4)) return 64; int n = (int)MathCeil(2.0 * M_PI / step); if(n < 8) n = 8; if(n > 256) n = 256; return n; }
This is Part 7's StepForRadius reasoning, applied to the disc a round cap or a round join is made of: the error of a chord against its arc is what CairoFlattenTolerance bounds, so a 2-pixel round cap gets a handful of sides and a 40-pixel one gets many. The floor of 8 exists because below that the eye reads a polygon rather than a circle however correct the arithmetic was, and the ceiling of 256 exists because a radius large enough to ask for more is a radius the caller got wrong.
Dashes
A dash pattern is a list of lengths, alternating on and off, walked along the path as a distance:
//+-------------------------------------------------------------------+ //| Install a dash pattern: on, off, on, off, in pixels. | //+-------------------------------------------------------------------+ bool CCairoStroker::SetDash(const double &pattern[], const int count, const double offset) { if(count <= 0) { ClearDash(); return true; } if(ArraySize(pattern) < count) return false; //--- a pattern of all zeros would never advance; refuse it rather //--- than loop forever looking for the end of the first dash double total = 0.0; for(int i = 0; i < count; i++) { if(pattern[i] < 0.0) return false; total += pattern[i]; } if(!(total > CAIRO_STROKE_EPSILON)) return false; //--- an odd pattern is doubled, so that "on" and "off" alternate //--- correctly on the second pass through it const int n = ((count & 1) != 0) ? count * 2 : count; if(ArrayResize(m_dashes, n) < n) return false; for(int i = 0; i < n; i++) m_dashes[i] = pattern[i % count]; m_dash_count = n; m_dash_offset = offset; return true; }
Two details are worth the lines they cost. An all-zero pattern is refused rather than accepted, because the dash walker advances by the current entry's length and a pattern that never advances is an infinite loop — a hang, not a wrong picture. A single zero inside a pattern is a different case and is allowed; the end of this section says why it is safe. And an odd-length pattern is doubled, because { 5 } has to mean "five on, five off": walked as the one-entry list it is, the roles would swap on every pass, so the pattern would alternate its own meaning. Every other graphics API reads an odd pattern the same way.

The offset shifts the pattern along the line. Advancing it a little on every frame is exactly how a marching-ants selection is animated, and the demo exposes it as an input so the effect can be seen without writing a timer.
Installing a pattern is half of it. The other half is StrokeDashed, which walks the contour at constant speed with the pattern running alongside. The offset is folded into one period first — MathMod against the pattern total, then a total added back if the result came out negative, so an offset of any size or sign lands inside the pattern — and the index is then advanced until what is left of the offset is shorter than the current entry, which is where the walk begins.
From there each segment is consumed in steps of whichever is shorter, the remainder of the current entry or the remainder of the segment. That is what makes a dash fall where the pattern says rather than where a vertex happens to be. Points are collected into the second scratch buffer while the pattern is "on", and when the entry runs out the collected run is stroked as its own open polyline — which is why a dashed line gets a cap at both ends of every dash instead of only at the ends of the line, and why a round-capped dashed line reads as a row of lozenges. A closed contour is walked with its wrap segment included, and whatever is still collected when the last segment ends is flushed as a final dash.
Which answers the zero left open above. A zero entry in the middle of a pattern does not advance the distance, but it does advance the index, so the walker reaches a non-zero entry within one pass of the pattern and the loop ends. { 0, 5 } walks; only { 0, 0 }, where there is no non-zero entry to reach, would not, and that is the pattern the sum test refuses. What a zero produces is a cut with no gap at it: two dashes meeting end to end, each carrying its own pair of caps.
The context learns to stroke
Context.mqh gains the settings, and they go in the state — because anything a setter changes has to be restorable, which was the rule Part 10 set:
//--- PART 11: the line settings. The width is in USER units, like //--- every coordinate the caller writes, and is converted to pixels //--- at stroke time - which is what makes a scaled drawing's //--- borders scale with it. double line_width; ENUM_CAIRO_CAP cap; ENUM_CAIRO_JOIN join; double miter;
//--- PART 11: the dash pattern, in USER units exactly like //--- line_width, and converted at stroke time for the same reason. //--- A fixed array rather than a dynamic one, because the state is //--- copied by assignment and a dynamic array would be shared. double dash[CAIRO_MAX_DASH]; int dash_count; double dash_offset;
The fixed array is a deliberate constraint, and the comment says why. Save() pushes the state with a single struct assignment; a dynamic array member would be copied by reference, so every saved level would share one pattern and Restore() would hand back whatever the innermost call had set. CAIRO_MAX_DASH is 8 — four on/off pairs, which covers the patterns an interface asks for and does not cover everything that is legal. SVG and PostScript put no bound on the list, so a longer pattern copied out of a stylesheet is rejected by SetDash rather than truncated, and a caller who needs one has to raise the constant. It is one #define wide, and it sits at 8 because every saved state carries the whole array and the state is copied on every Save().
The conversion, which is the whole point of storing them in user units
//+-------------------------------------------------------------------+ //| Stroke the current path. | //+-------------------------------------------------------------------+ void CCairoContext::StrokePreserve() { const double scale = m_state.ctm.ScaleFactor(); m_stroker.SetWidth(m_state.line_width * scale); m_stroker.SetCap(m_state.cap); m_stroker.SetJoin(m_state.join); m_stroker.SetMiterLimit(m_state.miter); if(m_state.dash_count > 0) { double dev[CAIRO_MAX_DASH]; for(int i = 0; i < m_state.dash_count; i++) dev[i] = m_state.dash[i] * scale; m_stroker.SetDash(dev, m_state.dash_count, m_state.dash_offset * scale); } else m_stroker.ClearDash(); if(!m_stroker.Stroke(m_path, m_stroke_path)) return; //--- the outline is always filled with the non-zero rule: it is a //--- pile of overlapping pieces, and even-odd would cancel them FillInto(m_stroke_path, ActiveSource(), CAIRO_NONZERO); }
The stroker works in device space, because a line width is a number of pixels. The path is already there — every vertex was transformed as it was built, back in Part 10 — so the width is the only thing left to convert, and the conversion is ScaleFactor(), the function Part 10 spent a section getting right.
This split imposes a condition on the caller: the path vertices and the stroke parameters are read at different times. A vertex is transformed when it is added; the width, the dashes and the dash offset are transformed here, at the stroke. If you change the transform in between (eg, call Scale after the last LineTo, or Restore a different matrix), the geometry keeps the old transform but the stroke width uses the new one. Nothing fails and nothing is reported; the line is simply the wrong thickness for the shape it outlines. The order to keep is: set the transform, build the path, stroke it, and only then change the transform again.
Under a non-uniform scale, a stroke is strictly an ellipse swept along the path rather than a circle, and this takes the larger axis. That is a conservative approximation and not a cheaper route to the same picture: the thin axis comes out as wide as the fat one, so under a 4-by-1 scale a line running along the squashed direction is drawn four times wider than it should be, round caps and round joins come out as circles where they should be ellipses, and the dash lengths take the same single factor, so the on and off stretches are measured in the larger unit whichever way they run. The alternative is transforming the outline instead of the width, which costs a second pass over the geometry — and a stroker that works in user units — to serve a case that almost never arises in an interface. Where the approximation shows, it errs thick, which reads as a heavy line rather than as a gap.
The dash lengths are converted for the same reason they are stored in user units. Dashes that kept their pixel lengths through a zoom would be a different pattern at every scale, while the line they are cut from got wider.
Note the last line, and the comment above it: the fill rule used here is notm_state.rule. A stroke outline is always non-zero, whatever the caller set for fills, because that is what welds the pieces.
There is a consequence for Restore() worth naming, because it is the kind of thing that looks like an omission. Restore() puts the clip and the state back and installs nothing in the stroker — not the width, not the cap, not the join, not the dashes. It cannot usefully do so: every one of those settings is held in user units and the stroker wants device pixels, and only the code above knows the conversion, because only it knows the transform in force at the moment of the stroke. Re-installing a user-space width in Restore() would change nothing that gets drawn, since the next stroke overwrites it — but Stroker().Width(), read in between, would return a user number from a getter that documents a device one. The rule the state keeps is simple: the state is the truth, and the stroker is a scratch pad rebuilt from it.
And the one that saves four lines everywhere
//+-------------------------------------------------------------------+ //| Fill and then stroke the same geometry. | //+-------------------------------------------------------------------+ void CCairoContext::FillStroke(const uint fill_argb, const uint stroke_argb) { SetSourceColor(fill_argb); FillPreserve(); SetSourceColor(stroke_argb); Stroke(); }
A body and a border is the shape of nearly every widget, and the order matters: stroke first and the fill paints over the inner half of the border. One method makes that impossible to get wrong.
The demo
Demo11_Stroke.mq5, seven panels.

Panel A draws one segment at five widths, from a 0.5-pixel hairline to 12 pixels. The hairline is not refused and not rounded up — it comes out as a row at half coverage, because coverage was never limited to whole pixels. A grey tick at the end of each line marks where the geometry stops.
Panel B draws the three caps against two vertical rules, so the difference between stopping at the rule, covering half a width past it, and rounding off is a measurement rather than an impression. The path itself is then drawn over each one as a one-pixel line in the background color, which makes the cap visibly an addition to the geometry rather than part of it.
Panel C is the three joins at a sharp bend and at a shallow one. The miter is dramatically the longest on the left and indistinguishable from the others on the right, which is the whole argument for why the limit only matters where the geometry is tight.
Panel D draws one very sharp bend twice, with the miter limit at 12 and then at 2. Nothing about the path changes; the join falls back to a bevel on the right because the spike lost.
Panel E is four dash patterns, including the odd-length { 14 }, and a fifth line that takes its offset from an input.
Panel F is the one worth running yourself. On the left, a rounded rectangle filled and stroked — what a widget looks like. On the right, the same stroke, except that the outline the stroker produced is itself stroked with a hairline instead of being filled:
if(st.Stroke(src, outline)) { //--- the outline is a PATH. Stroking it with a hairline shows //--- every contour the stroker emitted, instead of the welded //--- result the non-zero rule would produce.
Every quad, every wedge and every disc appears as the separate closed contour it is, overlapping its neighbors. The panel also prints the point count of the outline to the log, which for a rounded rectangle with round joins is in the hundreds.
Panel G is a 240-point price line with round joins and round caps, drawn under a translation, with a dashed zero line through the same coordinates. This is the shape of every chart overlay the library will ever be asked for, and the loop that builds it writes plain xs[i], ys[i] and knows nothing about strokes, transforms or dashes.

And the border that the fragment at the top of this article drew with six lines and four rectangles, leaving the panel's body to a separate fill, is now done with two lines:
g_ctx.Rect(x + 0.5, y + 0.5, w - 1.0, h - 1.0); g_ctx.FillStroke(C_CARD, C_LINE);
The half-pixel inset is the oldest trick in 2D drawing and it is worth knowing why it works. A one-pixel line centered on an integer coordinate straddles two pixel columns at half coverage each, so it renders as a two-pixel grey smear. Centered on x.5 it lands inside a single column at full coverage, and comes out as the crisp one-pixel line the caller asked for.
Project structure
MQL5/
├── Include/
│ └── CairoG2D/
│ ├── Color.mqh // the ARGB color type and blending
│ ├── Config.mqh // CairoAaSamples, CairoFlattenTolerance
│ ├── Surface.mqh // pixel buffer bound to one chart object
│ ├── Clip.mqh // CCairoClip — the rectangle, the mask, the coverage
│ ├── Path.mqh // the path and the edges, bounds, contains
│ ├── Paint.mqh // the color source, solid and gradient
│ ├── Raster.mqh // the coverage fill and the fill rule
│ ├── Context.mqh // CCairoContext — the object an application talks to
│ ├── Matrix.mqh // SCairoMatrix — the six-number affine transform
│ ├── Stroke.mqh // CCairoStroker — caps, joins, the miter limit, dashes
│ └── DemoTheme.mqh // the demos' shared palette - NOT library code
└── Experts/
└── CairoG2D/
└── Article 11/
└── Demo11_Stroke.mq5 // seven panels: widths, caps, joins, the miter limit, dashes, the raw outline, a price line Stroke.mqh includes Config.mqh and Path.mqh and nothing else. It does not know what a surface, a paint, a clip or a context is — it reads a path and writes a path, and everything else in the library is somebody else's problem. That is why it could be added without touching the rasterizer.
| # | File | Directory | Contents |
|---|---|---|---|
| 1 | Color.mqh | MQL5/Include/CairoG2D | ARGB color, CairoLerp, compositing |
| 2 | Config.mqh | MQL5/Include/CairoG2D | the two quality dials |
| 3 | Surface.mqh | MQL5/Include/CairoG2D | pixel buffer to chart bitmap |
| 4 | Matrix.mqh | MQL5/Include/CairoG2D | SCairoMatrix — the six-number affine transform |
| 5 | Path.mqh | MQL5/Include/CairoG2D | the geometry layer, untouched today |
| 6 | Paint.mqh | MQL5/Include/CairoG2D | CCairoPaint, the gradients, CCairoFillStyle |
| 7 | Clip.mqh | MQL5/Include/CairoG2D | CCairoClip — the rectangle, the mask, the coverage |
| 8 | Raster.mqh | MQL5/Include/CairoG2D | the scanline fill, untouched today |
| 9 | Stroke.mqh | MQL5/Include/CairoG2D | CCairoStroker — caps, joins, the miter limit, dashes |
| 10 | Context.mqh | MQL5/Include/CairoG2D | the line settings and Stroke |
| 11 | DemoTheme.mqh | MQL5/Include/CairoG2D | the shared light palette — not library code |
| 12 | Demo11_Stroke.mq5 | MQL5/Experts/CairoG2D/Article 11/ | seven panels: widths, caps, joins, the miter limit, dashes, the raw outline, a price line |
| 13 | Cairo Style Library - Part 11.zip | archive containing all the attached files and their paths relative to the terminal's root folder. |
The library can draw a line
A stroke is not a new kind of drawing operation. It is a path transformation: one path goes in, another comes out, and the resulting path is filled by the same rasterizer that has been handling fills since Part 3. Everything that makes stroking look complex — end caps, joins, miter limits, and dash patterns — is geometry that is calculated before any pixels are touched.
The design decision made at the beginning of Stroke.mqh is what keeps the implementation relatively simple. Instead of trying to detect and resolve self-intersections, the stroker emits overlapping geometry and lets the non-zero fill rule combine it. This works because overlaps are intentional and do not produce incorrect results. The trade-off is the number of edges, and that cost is significant. A dashed polyline with round joins and a few hundred points can generate several thousand edges, all of which the current rasterizer must sort on every scanline.
It is worth understanding what drives this number, because it is not determined by the point count alone. A round join or round cap contributes ArcSteps edges instead of just three or four, and this count increases with the line width and with a tighter CairoFlattenTolerance. Dash patterns multiply the geometry further, since each dash creates a separate segment with two end caps. Finally, the rasterizer performs its sweep for every scanline, so the same outline requires more work when rendered inside a tall panel than inside a short one.
This edge count is now the largest in the library, and reducing the associated processing cost will be the subject of a later part in this series.
Before that, there is another limitation to address, this time in the paint system. The engine can position geometry anywhere, fill it with a solid color or gradient, clip it, and stroke it. However, gradients are still limited to the two types introduced in Part 8. They are anchored to the shape's bounding box and cannot repeat, reflect, or have an independent transform. Without independent placement, a gradient cannot easily be used to draw a gauge sweep or a tiled background. The next part addresses this limitation.
The project is supported on MQL5 Algo Forge. Each part of this series has its own release, frozen at exactly the code explained in that part. This means that whichever article you are reading, you can download the corresponding release and work with the same implementation.
Part 11 is here: https://forge.mql5.io/SandroBegashvil/CairoG2D/releases/tag/part-11
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.