我想創建一個放在另一個圖像上的文本圖像。文字需要有白色填充和黑色筆畫輪廓。我使用的是Objective-C,它適用於iPhone。我可以讓文字出現;然而,我不能縫合以找出如何獲得筆畫並填充顏色來改變。如何在iPhone的UIGraphicsImageContext中使用屬性(特別是筆畫和填充顏色)繪製文本
self.bigImage
是一個指向我xib中的UIImage的指針。
這裏是我的代碼:(此代碼的工作......我希望它有一個黑色的中風但是白色填充)
- (IBAction)submitBtn:(id)sender {
UIFont *myfont = [UIFont fontWithName:@"myfont" size:32];
UIImage *textImage = [self imageFromText:@"teststring" font:myfont];
CGSize finalSize = [self.bigImage.image size];
CGSize textSize = [textImage size];
UIGraphicsBeginImageContext(finalSize);
[self.bigImage.image drawInRect:CGRectMake(0,0, finalSize.width, finalSize.height)];
[textImage drawInRect:CGRectMake(0, 0, textSize.width, textSize.height)];
UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.bigImage.image = newImg;
}
-(UIImage *)imageFromText:(NSString *)text font:(UIFont *)font {
CGSize size = [text sizeWithFont:font];
// check if UIGraphicsBeginImageContextWithOptions is available (iOS is 4.0+)
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);
else
// iOS is < 4.0
UIGraphicsBeginImageContext(size);
[text drawAtPoint:CGPointMake(0.0, 0.0) withFont:font];
// transfer image
UIImage *Image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return Image;
}
我可以得到它來呈現一個或另一個。如果我添加此代碼,我得到一個黑色的行程:
CGContextSetTextDrawingMode(UIGraphicsGetCurrentContext(), kCGTextStroke);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor blackColor] CGColor]);
如果我添加此代碼,我得到一個白色字體
CGFloat fontColor[4] = {255,255,255,1};
CGContextSetFillColor(UIGraphicsGetCurrentContext(), fontColor);
,但如果我同時添加snipets我得到的黑色中風但字體顏色是透明...
解決:得益於「布朗康」一點幫助:
我需要drawAtPoint
之前添加的這段代碼:
CGFloat fontColor[4] = {255,255,255,1};
CGContextSetFillColor(UIGraphicsGetCurrentContext(), fontColor);
CGContextSetTextDrawingMode(UIGraphicsGetCurrentContext(), kCGTextFillStroke);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor blackColor] CGColor]);
我不是在尋找使背景顏色爲白色,但字體本身白加黑中風。我希望背景的顏色透明。 – werdsackjon 2013-02-25 20:06:13