簡體   English   中英

將大綱/筆觸效果添加到UITextView ios <7

[英]Add Outline/Stroke effect to UITextView ios <7


我正在尋找在UITextView中為文本添加大綱/筆划的解決方案
對於UILabel,我可以通過覆蓋- (void)drawTextInRect:(CGRect)rect輕松完成此操作
我也找到了一些解決方案,但它們對我不起作用:
- 對於iOS 7,我發現這可以通過使用NSString方法解決: drawInRect:rect withAttributes: like this

- (void)drawRect:(CGRect)rect
{
    NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];

    // Define the font and fill color
    [stringAttributes setObject: self.font forKey: NSFontAttributeName];
    [stringAttributes setObject: self.textColor forKey: NSForegroundColorAttributeName];
    // Supply a negative value for stroke width that is 2% of the font point size in thickness
    [stringAttributes setObject: [NSNumber numberWithFloat: -2.0] forKey: NSStrokeWidthAttributeName];
    [stringAttributes setObject: self.strokeColor forKey: NSStrokeColorAttributeName];

    // Draw the string
    [self.text drawInRect:rect withAttributes:stringAttributes];
}

是否有任何可以支持iOS <7的解決方案? 謝謝

我更新了有人也在尋找這個問題的答案。
子類UITextView並覆蓋drawRect函數,如下所示

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGSize size = [self.text sizeWithFont:self.font constrainedToSize:rect.size lineBreakMode:NSLineBreakByWordWrapping];
    CGRect textRect = CGRectMake((rect.size.width - size.width)/2,(rect.size.height - size.height)/2, size.width, size.height);

    //for debug
    NSLog(@"draw in rect: %@", NSStringFromCGRect(rect));
    NSLog(@"content Size : %@", NSStringFromCGSize(self.contentSize));
    NSLog(@"Text draw at :%@", NSStringFromCGRect(textRect));

    CGContextRef textContext = UIGraphicsGetCurrentContext();
    CGContextSaveGState(textContext);
    //set text draw mode and draw the stroke
    CGContextSetLineWidth(textContext, 2); // set the stroke with as you wish
    CGContextSetTextDrawingMode (textContext, kCGTextStroke);

    CGContextSetStrokeColorWithColor(textContext, [UIColor blackColor].CGColor);

    [self.text drawInRect:textRect withFont:self.font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
    CGContextRestoreGState(textContext);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM