2014-05-04 77 views
8

我試圖在UIImage中切出一個透明的方塊,但是我真的不得不知道在哪裏/如何開始。如何在UIImage中「切割」透明洞?

任何幫助將不勝感激。

謝謝!

+1

你想切孔在_image_或在顯示它的UIImageView? – matt

+1

看看我在這個代碼中如何在UIImageView(及其圖像)中打出一個圓孔:http://stackoverflow.com/a/8632731/341994你會做同樣的事情,除非你畫一個正方形而不是圈。 – matt

+0

@matt:在實際的UIImageView中切割一個洞實際上是完美的!除了,我不知道如何使用你鏈接的代碼:p什麼是CLayer和CGContextRef? 謝謝! – Phillip

回答

15

假設您的圖像正在視圖中顯示 - 可能是一個UIImageView。然後我們可以通過在該視圖中打一個矩形孔,掩蓋視圖的層。每個視圖都有一個圖層。我們將在這個視圖的圖層上應用一個蒙版,它本身就是一個包含圖像的圖層,我們將在代碼中生成圖像。除了中間的某個明顯的矩形外,圖像將是黑色的。該明確的矩形將在圖像視圖中產生孔。

所以,讓self.iv成爲這個UIImageView。嘗試運行這樣的代碼:

CGRect r = self.iv.bounds; 
CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired! 
UIGraphicsBeginImageContextWithOptions(r.size, NO, 0); 
CGContextRef c = UIGraphicsGetCurrentContext(); 
CGContextAddRect(c, r2); 
CGContextAddRect(c, r); 
CGContextEOClip(c); 
CGContextSetFillColorWithColor(c, [UIColor blackColor].CGColor); 
CGContextFillRect(c, r); 
UIImage* maskim = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
CALayer* mask = [CALayer layer]; 
mask.frame = r; 
mask.contents = (id)maskim.CGImage; 
self.iv.layer.mask = mask; 

例如,在該圖像中,白方塊不是重疊正方形,它是一個孔,示出了窗口的背景的背後的白色:

enter image description here

編輯:我覺得有義務,因爲我在評論中提到它,以顯示如何用CAShapeLayer做同樣的事情。其結果是完全一樣的:

CGRect r = self.iv.bounds; 
CGRect r2 = CGRectMake(20,20,40,40); // adjust this as desired! 
CAShapeLayer* lay = [CAShapeLayer layer]; 
CGMutablePathRef path = CGPathCreateMutable(); 
CGPathAddRect(path, nil, r2); 
CGPathAddRect(path, nil, r); 
lay.path = path; 
CGPathRelease(path); 
lay.fillRule = kCAFillRuleEvenOdd; 
self.iv.layer.mask = lay; 
+0

這工作完美,謝謝噸馬特! 我還在讀你鏈接的東西,但它的真棒知道我有工作代碼引用:D 再次感謝的人,你真棒! :) – Phillip

+1

真的很酷的部分(許多之一)是,這對_any_ UIView工程。你可以在_anything_上打洞。此外,您可以打一個半透明的洞,而不是打出一個純粹的洞。另外,我們在這裏所做的並不是唯一的方法;我們可以使用CAShapeLayer作爲我們的面具,而不是製作圖像。 – matt

+0

那/很酷!我一定會記住這一點,如果我需要再次做這樣的事情:D – Phillip

5

這裏有一個簡單的斯威夫特功能cut#hole#inView複製和粘貼爲2017年

func cut(hole: CGRect, inView v: UIView) { 
    let p:CGMutablePath = CGMutablePath() 
    p.addRect(inView.bounds) 
    p.addRect(hole) 

    let s = CAShapeLayer() 
    s.path = p 
    s.fillRule = kCAFillRuleEvenOdd 

    v.layer.mask = s 
}