Objc – Draw text along UIImage

The NSTextContainer class defines a region in which text is laid out. An NSLayoutManager object uses one or more NSTextContainer objects to determine where to break lines, lay out portions of text, and so on. An NSTextContainer object defines rectangular regions, and you can define exclusion paths inside the text container’s bounding rectangle so that text flows around the exclusion path as it is laid out. You can create subclasses that define regions of nonrectangular shapes, such as circular regions.

Is introduced with iOS7. Reference: http://goo.gl/IGG0h6

You can finally use rich text view easily.
Here an example to draw a text using an UITextView along an UIImage inserted in center.

Schermata 2013-10-22 alle 14.27.44

How?

Nothing hard to do, you need to make an UIBezierPath, that is your shape.

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]UIBezierPath *circle = [ UIBezierPath bezierPathWithOvalInRect: rect ];
UIBezierPath *rect   = [ UIBezierPath bezierPathWithRect: rect ];
//[..][/code]

Next, pass it to the exclusionPaths parameter of the UITextView textContainer :

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]_myTextView.textContainer.exclusionPaths = @[circle];[/code]

You can also add an image or what you want.

Example:

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]- ( void ) drawText
{
_myTextView.text = @"Your very long text here…";

UIBezierPath *circle = [ UIBezierPath bezierPathWithOvalInRect: CGRectMake(105, 100, 120, 110) ];

UIImageView *imageView = [[ UIImageView alloc] initWithFrame:   CGRectMake(110, 110, 100, 102) ];

[imageView setImage: [UIImage imageNamed: @"yourImage.png"]];
[imageView setContentMode:UIViewContentModeScaleToFill];
[_myTextView addSubview: imageView];

_myTextView.textContainer.exclusionPaths = @[circle];
}[/code]

EOP

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.