gpt4 book ai didi

swift - 如何使用 CGContext 在 swift 中按程序绘制矩形/线

转载 作者:IT王子 更新时间:2023-10-29 05:15:12 25 4
gpt4 key购买 nike

几天来,我一直在网上搜索,试图找到有关如何在 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,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(size: imageSize)
imageView.image = image
}
}

func drawCustomImage(size: CGSize) -> UIImage {
// Setup our context
let bounds = CGRect(origin: .zero, size: size)
let opaque = false
let scale: CGFloat = 0
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
let context = UIGraphicsGetCurrentContext()!

// Setup complete, do drawing here
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(2)

context.stroke(bounds)

context.beginPath()
context.move(to: CGPoint(x: bounds.minX, y: bounds.minY))
context.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
context.move(to: CGPoint(x: bounds.maxX, y: bounds.minY))
context.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
context.strokePath()

// Drawing complete, retrieve the finished image and cleanup
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}

关于swift - 如何使用 CGContext 在 swift 中按程序绘制矩形/线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25229916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com