2011-07-11 175 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