import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let viewRect = CGRect(x: 50, y: 50, width: 100, height: 100)
let view1 = MyCanvas(frame: viewRect)
self.view.addSubview(view1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
class MyCanvas: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//把背景色设为透明
self.backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
//获取绘制上下文
let context = UIGraphicsGetCurrentContext()
//计算要在其中绘制的矩形
let pathRect = CGRectInset(self.bounds,
self.bounds.size.width * 0.1,
self.bounds.size.height * 0.1)
//创建一个圆角矩形路径
let rectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: 20)
//保存绘制设置
CGContextSaveGState(context)
//准备阴影
let shadowColor = UIColor.blackColor().CGColor
let shadowOffet = CGSize(width: 3, height: 3)
let shadowBlurRadius:CGFloat = 5.0
//创建和应用阴影
CGContextSetShadowWithColor(context, shadowOffet, shadowBlurRadius, shadowColor)
//绘制带有阴影的路径
UIColor.blueColor().setFill()
rectanglePath.fill()
//还原绘制设置
CGContextRestoreGState(context)
//绘制另一个矩形(不带阴影)
let pathRect2 = CGRectInset(self.bounds,
self.bounds.size.width * 0.3,
self.bounds.size.height * 0.3)
let rectanglePath2 = UIBezierPath(rect: pathRect2)
UIColor.yellowColor().setFill()
rectanglePath2.fill()
}
}
|