2011-07-11 10 views
19

Có thể thêm hình ảnh khác, nhỏ hơn, hình ảnh vào UIImage/UIImageView không? Nếu vậy, làm thế nào? Nếu không, sau đó làm thế nào tôi có thể vẽ một hình tam giác nhỏ đầy?Vẽ một hình ảnh khác trên UIImage

Cảm ơn

Trả lời

36

Bạn có thể thêm một subview để bạn UIImageView chứa hình ảnh khác với hình tam giác đầy nhỏ. Hoặc bạn có thể vẽ bên trong của hình ảnh đầu tiên:

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(); 

Mã này (source here) sẽ tạo ra một mới UIImage mà bạn có thể sử dụng để khởi tạo một UIImageView.

20

Bạn có thể thử này, hoạt động hoàn hảo đối với tôi, đó là UIImage loại:

- (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; 
} 

hoặc Swift:

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

Cảm ơn bạn anh chàng, đó là một đoạn rất hữu ích. –

+1

Điều này hoạt động tốt, cảm ơn bạn. Tôi đề nghị bạn sử dụng 'UIGraphicsBeginImageContextWithOptions (kích thước, false, 0)', mặc dù. Điều này sẽ cung cấp cho bạn một hình ảnh với độ phân giải chính xác cho màn hình. (Mặc định sẽ chỉ tạo ra ảnh x1, hầu như chắc chắn sẽ bị mờ.) – Womble