在UITextView for iPhone上绘制格线

Bob*_*ore 4 iphone uitextview

我想创建一个像iPhone上的笔记应用程序的视图,因此需要视图根据笔记应用程序有格线,我已经在窗口中完成了这一点,你需要获取字体指标,然后将线条绘制到设备上有没有人在UITextView中做过这个,如果这样的话会有一些帮助

Dav*_*ton 8

子类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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在初始化文本视图时,请确保将contentMode设置为UIViewContentModeRedraw.否则,行不会随文本滚动.

self.contentMode = UIViewContentModeRedraw;
Run Code Online (Sandbox Code Playgroud)

这并不完美.理想情况下,你应该只画入通过的矩形.但我很懒,这符合我的需要.


Bob*_*ore 5

我认为这个工作正常,但我觉得它已经被黑了,我没有完全理解UITextView类的机制;

首先,您必须将以下内容添加到您的委托,以强制重绘滚动

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{   
    // NSLog(@"scrollViewDidScroll The scroll offset is ---%f",scrollView.contentOffset.y);
    [noteText setNeedsDisplay];
}
Run Code Online (Sandbox Code Playgroud)

然后在子类中实现drawRect

- (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);
    }
}
Run Code Online (Sandbox Code Playgroud)

仍然担心这个神奇数字6

短发