Reputation: 2510
i'm trying draw background line of UITextView, here is the code i used to draw those lines
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, self.horizontalLineColor.CGColor);
CGContextSetLineWidth(context, kDashedBorderWidth);
CGContextSetLineDash(context, 0, kDashedLinesLength, kDashedCount) ;
CGFloat baseOffset = 9.0f + self.font.descender;
CGFloat boundsX = self.bounds.origin.x;
CGFloat boundsWidth = self.bounds.size.width;
NSInteger firstVisibleLine = MAX(1, (self.contentOffset.y / self.font.lineHeight));
NSInteger lastVisibleLine = ceilf((self.contentOffset.y + self.bounds.size.height) / self.font.lineHeight);
for (NSInteger line = firstVisibleLine; line <= lastVisibleLine; ++line)
{
CGFloat linePointY = (baseOffset + (self.font.lineHeight * (float)line));
CGContextMoveToPoint(context, boundsX, linePointY);
CGContextAddLineToPoint(context, boundsWidth, linePointY);
}
CGContextClosePath(context);
CGContextStrokePath(context);
And the result is shown in the picture
It seem like the it get the first line correctly but the following lines are not aligned with the text.
What did i probably miss here? Is there anything to do with localization setting?
Upvotes: 2
Views: 1756
Reputation: 2510
after few experiments, i figured out that the lineHeight
in fact is a bit smaller than the real height, about 1points size.
Here is working version
CGFloat baseOffset = 7.0f + self.font.descender;
// ....
for (NSInteger line = firstVisibleLine; line <= lastVisibleLine; ++line)
{
CGFloat linePointY = (baseOffset + ((self.font.lineHeight + 1.0f) * (float)line));
CGContextMoveToPoint(context, boundsX, linePointY);
CGContextAddLineToPoint(context, boundsWidth, linePointY);
}
There are two magic numbers i think you need to find out if you implement your own version : the 7.0f
and 1.0f
it is just a work around, i would love to know a better way to achieve this.
Upvotes: 2
Reputation: 14118
This is not the exact solution, but the way around for this UI. This UI gives a feel of underlined text.
Try using NSAttributedString with underlined property where you can provide dashed line as a pattern.
Using CoreText you can draw your text over view with kCTUnderlinePatternDash
property.
But I guess using this, we can achieve the same kind of functionality as you required.
Hope this helps.
Upvotes: 1