2017-01-24 25 views
0

我正在嘗試將文字繪製到UIImage。下面的這個方法可行,但是文本是關閉的。我在框架的中心有*l標籤。在self.image = [self drawText]之後,文本位於圖像的左上角。將文字添加到UIImage ...錯誤的地方

-(UIImage*) drawText{ 
    UIGraphicsBeginImageContextWithOptions(_creatorImageView.image.size, false, _creatorImageView.image.scale); 
    [_creatorImageView.image drawInRect:CGRectMake(0,0,_creatorImageView.image.size.width, _creatorImageView.image.size.height)]; 

    NSLog(@"Caption ARRY: %@", _creatorImageView.captionArray); 
    for (UILabel *l in _creatorImageView.captionArray){ 
     NSLog(@"%f %f", l.frame.origin.x, l.frame.origin.y); 
     CGRect rect = CGRectMake(l.frame.origin.x, l.frame.origin.y, _creatorImageView.image.size.width, _creatorImageView.image.size.height); 
     [l.textColor set]; 
     CGFloat radians = atan2f(l.transform.b, l.transform.a); 
     CGFloat degrees = radians * (180/M_PI); 

     //CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeScale(l.transform.tx, l.transform.ty)); 
     //CGContextConcatCTM(UIGraphicsGetCurrentContext(), CGAffineTransformMakeRotation(degrees)); 

     //NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new]; 
     //[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; 
     //[paragraphStyle setAlignment:NSTextAlignmentCenter]; 

     NSDictionary *attributes = @{ NSFontAttributeName: l.font, 
            NSForegroundColorAttributeName: l.textColor, 
            NSBackgroundColorAttributeName: l.backgroundColor}; 
            //NSParagraphStyleAttributeName:paragraphStyle}; 

     [l.text drawInRect:rect withAttributes:attributes]; 
     NSLog(@"TEXT: %@", l.text); 

    } 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return newImage; 
} 

回答

0

您正在使用的代碼

[l.text drawInRect:rect withAttributes:attributes]; 

要繪製文本。您指定的rect矩形控制文本在您的上下文座標中的位置(其中,0,0是上下文的左上角)。

如果您希望文本在您的上下文中居中,請計算中心如果你的上下文,並調整你的矩形的原點,在那裏文本居中。

我會讓你算出數學。這隻會是幾行代碼。

+0

'rect.x = 119.5'和'rect.y = 340.5'。這是標籤座標。這就是爲什麼我很困惑,爲什麼它在左上角。 @Duncan C. – Peter

相關問題