Как я могу преобразовать следующий код о Core Graphics в Swift? - PullRequest
0 голосов
/ 16 мая 2018
- (void) drawTextLink:(NSString *) text inFrame:(CGRect) frameRect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform ctm = CGContextGetCTM(context);

    // Translate the origin to the bottom left.
    // Notice that 842 is the size of the PDF page. 
    CGAffineTransformTranslate(ctm, 0.0, 842);

    // Flip the handedness of the coordinate system back to right handed.
    CGAffineTransformScale(ctm, 1.0, -1.0);

    // Convert the update rectangle to the new coordiante system.
    CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm);

    NSURL *url = [NSURL URLWithString:text];        
    UIGraphicsSetPDFContextURLForRect( url, xformRect );

    CGContextSaveGState(context);
    NSDictionary *attributesDict;
    NSMutableAttributedString *attString;

    NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle];
    attributesDict = @{NSUnderlineStyleAttributeName : underline, 
    NSForegroundColorAttributeName : [UIColor blueColor]};
    attString = [[NSMutableAttributedString alloc] initWithString:url.absoluteString attributes:attributesDict];

    [attString drawInRect:frameRect];

    CGContextRestoreGState(context);
}

Это код, который я нашел, чтобы сделать URL-адреса в PDF кликабельными.

Я все еще изучаю цель-c, поэтому ваша помощь очень ценится.Заранее большое спасибо!

Сейчас я перевёл вот что, и я уверен, что есть пара ошибок:

    func drawTextLink(text: NSString, frameRect: CGRect) {
let context: CGContext = UIGraphicsGetCurrentContext()!
    var c = context.ctm

    let cc = CGAffineTransform.translatedBy(c)
    cc.(0.0, 842)

}

1 Ответ

0 голосов
/ 16 мая 2018

Вышеуказанный метод в Swift 4.0 должен быть таким:

func drawTextLink(text: String, frame: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {return}
    let ctm = context.ctm
    ctm.translatedBy(x: 0.0, y: 842)
    ctm.scaledBy(x: 1.0, y: -1.0)
    let newFrame = frame.applying(ctm)
    guard let url = URL(string: text) else {return}
    UIGraphicsSetPDFContextURLForRect(url, newFrame)
    context.saveGState()
    let dict = [NSAttributedStringKey.underlineStyle: 1, .foregroundColor: UIColor.red] as [NSAttributedStringKey : Any]
    let attrString = NSAttributedString(string: text, attributes: dict)
    attrString.draw(in: frame)
    context.restoreGState()
}
...