2014-09-12 108 views
4

的內容邊界我有一個UIImageView與一個圖像是具有透明背景的一輛車:周圍繪製的UIImageView

enter image description here

而且我想提請圍繞汽車邊框:

enter image description here

如何才能達到此效果?

目前,我已經以這種方式測試CoreGraphics中,但沒有很好的效果:

// load the image 
    UIImage *img = carImage; 

    UIGraphicsBeginImageContext(img.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [[UIColor redColor] setFill]; 
    CGContextTranslateCTM(context, 0, img.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    CGContextSetBlendMode(context, kCGBlendModeNormal); 
    CGRect rect = CGRectMake(0, 0, img.size.width * 1.1, img.size.height*1.1); 
    CGContextDrawImage(context, rect, img.CGImage); 

    CGContextClipToMask(context, rect, img.CGImage); 
    CGContextAddRect(context, rect); 
    CGContextDrawPath(context,kCGPathFill); 

    // generate a new UIImage from the graphics context we drew onto 
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

任何幫助嗎?謝謝。

回答

7

這裏就是我所做的:

我這樣做是在斯威夫特只是爲了檢查它遊樂場,認爲你可以將其轉化爲Objective-C的容易:

import UIKit 


func drawOutlie(#image:UIImage, color:UIColor) -> UIImage 
{ 
    var newImageKoef:CGFloat = 1.08 

    var outlinedImageRect = CGRect(x: 0.0, y: 0.0, width: image.size.width * newImageKoef, height: image.size.height * newImageKoef) 

    var imageRect = CGRect(x: image.size.width * (newImageKoef - 1) * 0.5, y: image.size.height * (newImageKoef - 1) * 0.5, width: image.size.width, height: image.size.height) 

    UIGraphicsBeginImageContextWithOptions(outlinedImageRect.size, false, newImageKoef) 

    image.drawInRect(outlinedImageRect) 

    var context = UIGraphicsGetCurrentContext() 
    CGContextSetBlendMode(context, kCGBlendModeSourceIn) 

    CGContextSetFillColorWithColor(context, color.CGColor) 
    CGContextFillRect(context, outlinedImageRect) 
    image.drawInRect(imageRect) 

    var newImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

    return newImage 

} 

var imageIn = UIImage(named: "158jM") 

var imageOut = drawOutlie(image: imageIn, UIColor.redColor()) 

所以它是如何工作的?

  1. 我們創造清潔環境(又名帆布)用大一點的大小,則原始圖像(輪廓)
  2. 我們利用整個畫布
  3. 我們的形象,我們填補圖像與色彩
  4. 我們借鑑在上面

較小的圖像,您可以更改外形尺寸更改此屬性:var newImageKoef:CGFloat = 1.08

這是我在遊樂場的結果

enter image description here