我想创建一个类似于iPhone上的笔记应用程序的视图,因此需要该视图具有笔记应用程序中的横线。 我已经在Windows中完成了这个工作,您需要获取字体度量值,然后将线条绘制到设备上下文中。如果在UITextView中完成过此操作,则需要一些帮助。
我想创建一个类似于iPhone上的笔记应用程序的视图,因此需要该视图具有笔记应用程序中的横线。 我已经在Windows中完成了这个工作,您需要获取字体度量值,然后将线条绘制到设备上下文中。如果在UITextView中完成过此操作,则需要一些帮助。
继承UITextView类。重写-drawRect:方法。
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);
CGContextSetLineWidth(context, self.lineWidth);
CGFloat strokeOffset = (self.lineWidth / 2);
CGFloat rowHeight = self.font.lineHeight;
if (rowHeight > 0) {
CGRect rowRect = CGRectMake(self.contentOffset.x, - self.bounds.size.height, self.contentSize.width, rowHeight);
while (rowRect.origin.y < (self.bounds.size.height + self.contentSize.height)) {
CGContextMoveToPoint(context, rowRect.origin.x + strokeOffset, rowRect.origin.y + strokeOffset);
CGContextAddLineToPoint(context, rowRect.origin.x + rowRect.size.width + strokeOffset, rowRect.origin.y + strokeOffset);
CGContextDrawPath(context, kCGPathStroke);
rowRect.origin.y += rowHeight;
}
}
}
当您初始化文本视图时,请确保将contentMode设置为UIViewContentModeRedraw。否则,行不会随着文本滚动。
self.contentMode = UIViewContentModeRedraw;
这不是最完美的。理想情况下,你应该只需绘制传递的矩形。但我懒惰了,这对我的需求起作用。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// NSLog(@"scrollViewDidScroll The scroll offset is ---%f",scrollView.contentOffset.y);
[noteText setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
// Drawing code
// Get the graphics context
CGContextRef ctx = UIGraphicsGetCurrentContext();
[super drawRect:rect];
// Get the height of a single text line
NSString *alpha = @"ABCD";
CGSize textSize = [alpha sizeWithFont:self.font constrainedToSize:self.contentSize lineBreakMode:UILineBreakModeWordWrap];
NSUInteger height = textSize.height;
// Get the height of the view or contents of the view whichever is bigger
textSize = [self.text sizeWithFont:self.font constrainedToSize:self.contentSize lineBreakMode:UILineBreakModeWordWrap];
NSUInteger contentHeight = (rect.size.height > textSize.height) ? (NSUInteger)rect.size.height : textSize.height;
NSUInteger offset = 6 + height; // MAGIC Number 6 to offset from 0 to get first line OK ???
contentHeight += offset;
// Draw ruled lines
CGContextSetRGBStrokeColor(ctx, .8, .8, .8, 1);
for(int i=offset;i < contentHeight;i+=height) {
CGPoint lpoints[2] = { CGPointMake(0, i), CGPointMake(rect.size.width, i) };
CGContextStrokeLineSegments(ctx, lpoints, 2);
}
}
仍然担心这个神奇数字6
Bob
self.contentMode = UIViewContentModeRedraw;
添加到子类的init方法中,而不是你的setNeedsDisplay
方法。 - reggiantextView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"RuledLinesPage.png"]];
如果要填充颜色的区域大于图像,则使用带有图案的颜色会创建平铺图像。因此,您必须确保图像大小是正确的/可平铺的(我不认为“可平铺”是一个真正的词,但我希望您明白我的意思)。此外,您还需要创建具有规则线条的图像,以最好地匹配您的textView字体。
祝你好运。