2011-07-11 49 views
19

是否可以向UIImage/UIImageView添加另一个较小的图像?如果是这样,怎么样?如果不是,那我怎么画一个小的实心三角形?在UIImage上绘制另一个图像

感谢

回答

36

你可以一个子视图添加到您的UIImageView包含与小实心三角形另一个图像。或者你可以绘制的第一个图像内:

CGFloat width, height; 
UIImage *inputImage; // input image to be composited over new image as example 

// create a new bitmap image context at the device resolution (retina/non-retina) 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 0.0);   

// get context 
CGContextRef context = UIGraphicsGetCurrentContext();  

// push context to make it current 
// (need to do this manually because we are not drawing in a UIView) 
UIGraphicsPushContext(context);        

// drawing code comes here- look at CGContext reference 
// for available operations 
// this example draws the inputImage into the context 
[inputImage drawInRect:CGRectMake(0, 0, width, height)]; 

// pop context 
UIGraphicsPopContext();        

// get a UIImage from the image context- enjoy!!! 
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); 

// clean up drawing environment 
UIGraphicsEndImageContext(); 

此代码(source here)将创建一个新UIImage,你可以用它来初始化一个UIImageView

20

你可以试试这个,完美的作品对我来说,这是UIImage的类别:

- (UIImage *)drawImage:(UIImage *)inputImage inRect:(CGRect)frame { 
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0); 
    [self drawInRect:CGRectMake(0.0, 0.0, self.size.width, self.size.height)]; 
    [inputImage drawInRect:frame]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 

或斯威夫特:

extension UIImage { 
    func image(byDrawingImage image: UIImage, inRect rect: CGRect) -> UIImage! { 
     UIGraphicsBeginImageContext(size) 
     draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) 
     image.draw(in: rect) 
     let result = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return result 
    } 
} 
+0

谢谢你,伙计,这是一个非常有用的片段。 –

+1

这个效果很好,谢谢。不过,我建议你使用'UIGraphicsBeginImageContextWithOptions(size,false,0)'。这将为您提供屏幕正确分辨率的图像。 (默认情况下只会生成一张x1图像,这几乎肯定会模糊。) – Womble

相关问题