Greg Greg - 5 months ago 36
iOS Question

Crosshatch in IOS using CoreGraphics?

How would one crosshatch (apply a set of parallel lines at 45 degrees) across the fill of a shape in IOS using core graphics? Sample code?

(I'm specially interested in use with an MKPolygon in MKMapKit, however for the moment just trying to see if it's possible in a UIView using drawRect?. So fill the background of a UIView with crosshatch'ing)

Answer

Create a UIImage containing your crosshatch pattern in whatever way you want (e.g. by drawing it with Core Graphics or by loading it from a PNG file).

Then use +[UIColor colorWithPatternImage:] (Swift UIColor(patternImage:)) to create a “color” that draws the crosshatch image.

Finally, set the pattern color as your fill color, and fill the shape (presumably by filling a path that outlines the shape, or by using UIRectFill).

If you need more control over the pattern (to change how it's tiled or aligned), you can drop down to the Core Graphics level and use CGPatternCreate and CGColorCreateWithPattern.

Comments