2011-07-11 13 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)あなたはUIImageViewを初期化するために使用できる新しいUIImageを作成します。

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