- (void)viewDidLoad { [super viewDidLoad]; UIImage *image = [self drawImageAtImageContext]; UIImageView *imageView = [[UIImageView alloc]initWithImage:image]; imageView.center = CGPointMake(160, 282); [self.view addSubview:imageView]; } //添加水印 -(UIImage *)drawImageAtImageContext{ //得到一個位圖圖形上下文 CGSize size = CGSizeMake(300, 188);//畫布大小 UIGraphicsBeginImageContext(size); UIImage *image = [UIImage imageNamed:@"frame_shop_lovely_bg@2x.jpg"]; //注意繪圖的位置是相對於畫布頂點而言,不是屏幕 [image drawInRect:CGRectMake(0, 0, 300, 188)]; //添加水印 CGContextRef ref = UIGraphicsGetCurrentContext(); //字符的長度和 font UIFont *font = [UIFont systemFontOfSize:15]; NSString *str = @"大金毛"; int strLength = str.length *font.pointSize; //兩點肯定一條直線 //下劃線的長度等於字符長度 CGContextMoveToPoint(ref, 200, 178); CGContextAddLineToPoint(ref, strLength + 200, 178); //直線的顏色、寬度 [[UIColor redColor]setStroke]; CGContextSetLineWidth(ref, 2); //繪製圖像到指定圖形上下文,只有邊框 CGContextDrawPath(ref, kCGPathStroke); //字符的位置 [str drawInRect:CGRectMake(200, 158, 100, 30) withAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor redColor]}]; //返回繪製的新圖形 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //最後必定不要忘了關閉上下文 UIGraphicsEndImageContext(); return newImage; }