CFStringRef изменить цвет в Objective-c

Можно ли заменить color на CFStringRef?

Я хочу, чтобы текст red например, по умолчанию black, как я могу это изменить?

Я пробовал это:

  -(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{
    CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
    // Prepare the text using a Core Text Framesetter
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);

    CGMutablePathRef framePath = CGPathCreateMutable();
    CGPathAddRect(framePath, NULL, frameRect);

    CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
    CFAttributedStringReplaceString (attrString,CFRangeMake(0, 0), stringRef);

    CGColorRef _red=[UIColor redColor].CGColor;
    
    CFAttributedStringSetAttribute(attrString, CFRangeMake(0, [textToDraw length]),kCTForegroundColorAttributeName, _red);

    // Get the frame that will do the rendering.
    CFRange currentRange = CFRangeMake(0, 0);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
    CGPathRelease(framePath);
    
    // Get the graphics context.
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    
    // Put the text matrix into a known state. This ensures
    // that no old scaling factors are left in place.
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);

    // Core Text draws from the bottom-left corner up, so flip
    // the current transform prior to drawing.
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    
    // Draw the frame.
    CTFrameDraw(frameRef, currentContext);
    
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);

    CFRelease(frameRef);
    CFRelease(stringRef);
    CFRelease(framesetter);
}

Но текст черный.


person Adina Marin    schedule 22.06.2015    source источник
comment
пожалуйста, проверьте stackoverflow.com/questions/13738149/   -  person Nitin Gohel    schedule 22.06.2015
comment
это не работает для меня   -  person Adina Marin    schedule 22.06.2015
comment
Строка не имеет цвета, вы должны использовать AttributedString, как это предлагается в связанном вопросе из комментария. Что не работает из предыдущего ответа?   -  person Larme    schedule 22.06.2015
comment
я обновляю свой вопрос   -  person Adina Marin    schedule 22.06.2015
comment
Вы устанавливаете red color effect в диапазоне 0,0. Вам это кажется правильным?   -  person Larme    schedule 22.06.2015
comment
если я поставлю диапазон › 0, это сбой   -  person Adina Marin    schedule 22.06.2015
comment
В моем тесте он не разбился (я просто удалил фреймы, которые не связаны). Какой диапазон вы использовали? Каково значение [textToDraw length]? Если вы хотите раскрасить весь текст, вы должны в последней строке CFRangeMake(0, [textToDraw length]) или CFRangeMake(0, CFStringGetLength(stringRef).   -  person Larme    schedule 22.06.2015
comment
Я снова обновляю свой вопрос, но проблема та же :(   -  person Adina Marin    schedule 22.06.2015
comment
Я не использую CoreText, но вы, похоже, используете framesetter, но инициализируете его с помощью currentText (у которого нет понятия красного) вместо attrString. Может быть проблема.   -  person Larme    schedule 22.06.2015
comment
Теперь весь текст из pdf красный...   -  person Adina Marin    schedule 22.06.2015
comment
Ну значит работает правильно? Вы так и не сказали, какую часть вы хотите покрасить в красный цвет. Затем вы должны правильно применить к нужному диапазону.   -  person Larme    schedule 22.06.2015
comment
Большое спасибо за Вашу помощь !   -  person Adina Marin    schedule 22.06.2015


Ответы (1)


Я отредактировал ваш код для вашей цели

-(void)drawText:(NSString*)textToDraw
      withColor: (UIColor*) color
        inFrame:(CGRect)frameRect
{


    CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
    // Prepare the text using a Core Text Framesetter

    CGMutablePathRef framePath = CGPathCreateMutable();
    CGPathAddRect(framePath, NULL, frameRect);

    /// ATTRIBUTES FOR COLOURED STRING
    NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
    NSAttributedString *attString = [[NSAttributedString alloc] initWithString:textToDraw attributes:attrs];

    CTFramesetterRef framesetter =
    CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); //3
    CTFrameRef frameRef =
    CTFramesetterCreateFrame(framesetter,
                             CFRangeMake(0, [attString length]), framePath, NULL);


    // Get the graphics context.
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();

    // Put the text matrix into a known state. This ensures
    // that no old scaling factors are left in place.
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);


    // Core Text draws from the bottom-left corner up, so flip
    // the current transform prior to drawing.
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
    CGContextScaleCTM(currentContext, 1.0, -1.0);

    // Draw the frame.
    CTFrameDraw(frameRef, currentContext);

    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);


    CFRelease(frameRef);
    CFRelease(stringRef);
    CFRelease(framesetter);
}

Надеюсь это поможет.

person Doro    schedule 22.06.2015