项目介绍:
图片合成,部分截屏,不规则图片,简单实用
主要代码如下:
[Objective-C] 查看源文件 复制代码
class ViewController: UIViewController { @IBOutlet weak var changeImgButton: UIButton! var showImg: UIImage? { didSet { if showImg != nil { self.view.layer.contents = showImg?.CGImage } } } override func viewDidLoad() { super.viewDidLoad() self.setShowImg() self.view.bringSubviewToFront(self.changeImgButton) } func setShowImg() { let img1 = UIImage.init(named: "big") let img2 = UIImage.init(named: "small") showImg = self.createImage(Image1: img1!, Image2: img2!) } @IBAction func changeImg(sender: UIButton) { sender.selected = !sender.selected if sender.selected { showImg = self.imageAtFrame(CGRectMake(0, 0, 200, 200)) } else { self.setShowImg() self.anomalyPictture(Image: showImg!) } } func createImage(Image1 image1: UIImage,Image2 image2: UIImage) -> UIImage{ print(image1.size) print(self.view.bounds) UIGraphicsBeginImageContext(image1.size) image1.drawInRect(CGRectMake(0, 0, image1.size.width, image1.size.height)) image2.drawInRect(CGRectMake(20, 20, 100, 100)) let resultImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultImage! } /* 截图 */ func imageAtFrame(frame: CGRect) -> UIImage { UIGraphicsBeginImageContext(self.view.bounds.size) let context = UIGraphicsGetCurrentContext() //将下面两行去掉全屏截图 CGContextSaveGState(context) UIRectClip(frame) // self.view.layer.renderInContext(context!) let newImg = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImg } func anomalyPictture(Image image: UIImage) { let maskLayer = CAShapeLayer.init() maskLayer.path = UIBezierPath.init(ovalInRect: CGRectMake(0, 0, 200, 300)).CGPath maskLayer.fillColor = UIColor.greenColor().CGColor maskLayer.strokeColor = UIColor.orangeColor().CGColor maskLayer.lineWidth = 10 let contentLayer = CALayer.init() contentLayer.mask = maskLayer contentLayer.bounds = CGRectMake(0, 0, 200, 300) contentLayer.position = CGPointMake(self.view.center.x, self.view.center.y) contentLayer.backgroundColor = UIColor.redColor().CGColor contentLayer.contents = image.CGImage self.view.layer.addSublayer(contentLayer) } }
DEMO下载:
TestPictures.zip
(908.68 KB, 下载次数: 276)
2016-7-12 16:29 上传
点击文件名下载附件
图片操作