我已经拖网了几天,试图找到关于如何在Swift中以程序方式绘制矩形或线条的最简单的代码示例。我已经看到如何通过覆盖DrawRect命令来做到这一点。我相信你可以创建一个CGContext然后绘制一个图像,但我很乐意看到一些简单的代码示例。还是这是一个可怕的做法?谢谢。
class MenuController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. self.view.backgroundColor = UIColor.blackColor() var logoFrame = CGRectMake(0,118,40) var imageView = UIImageView(frame: logoFrame) imageView.image = UIImage(named:"logo") self.view.addSubview(imageView) //need to draw a rectangle here } }
这是一个创建一个包含透明背景和一个红色矩形的自定义UIImage的例子,线条通过对角线对齐。
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad(); let imageSize = CGSize(width: 200,height: 200) let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 100,y: 100),size: imageSize)) self.view.addSubview(imageView) let image = drawCustomImage(imageSize) imageView.image = image } } func drawCustomImage(size: CGSize) -> UIImage { // Setup our context let bounds = CGRect(origin: CGPoint.zeroPoint,size: size) let opaque = false let scale: CGFloat = 0 UIGraphicsBeginImageContextWithOptions(size,opaque,scale) let context = UIGraphicsGetCurrentContext() // Setup complete,do drawing here CGContextSetStrokeColorWithColor(context,UIColor.redColor().CGColor) CGContextSetLineWidth(context,2.0) CGContextStrokeRect(context,bounds) CGContextBeginPath(context) CGContextMoveToPoint(context,CGRectGetMinX(bounds),CGRectGetMinY(bounds)) CGContextAddLineToPoint(context,CGRectGetMaxX(bounds),CGRectGetMaxY(bounds)) CGContextMoveToPoint(context,CGRectGetMaxY(bounds)) CGContextStrokePath(context) // Drawing complete,retrieve the finished image and cleanup let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image }