我试图在触摸时绘制一个矩形。到目前为止我有两段代码,第一段是当前绘制圆形的方法,第二段代码添加了要查看的形状,如何绘制矩形?
func drawRectangle() {
// Get the Graphics Context
let context = UIGraphicsGetCurrentContext();
// Set the rectangle outerline-width
CGContextSetLineWidth(context, 5.0);
// Set the rectangle outerline-colour
UIColor.redColor().set()
// Create Rectangle
CGContextAddArc(context, (frame.size.width)/2, frame.size.height/2, (frame.size.width - 10)/2, 0.0, CGFloat(M_PI * 2.0), 1)
// Draw
CGContextStrokePath(context);
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let rectangleCenter = touches.first!.locationInView(view)
let rectangleWidth = CGFloat(50)
let rectangleHeight = rectangleWidth
// Create a new rectangleView
let rectangleView = Annotations(frame: CGRectMake(rectangleCenter.x, rectangleCenter.y, rectangleWidth, rectangleHeight), shape: 1)
view.addSubview(rectangleView)
}
我尝试了以下内容:
// Create Rectangle
CGContextAddRect(context, CGRectMake((frame.size.width)/2, frame.size.height/2, 40, 40));
它会创建矩形左上角的一部分,顶部有一条线,左边有一条线。如何将其调整为完整的矩形?
答案 0 :(得分:-1)
我能够通过以下方式解决我的问题:
增加宽度和高度:
let rectangleWidth = CGFloat(100)
let rectangleHeight = rectangleWidth
和我的矩形方法
func drawRectangle()
{
// Get the Graphics Context
let context = UIGraphicsGetCurrentContext();
// Set the rectangle outerline-width
CGContextSetLineWidth(context, 5.0);
// Set the rectangle outerline-colour
UIColor.redColor().set()
// Create Rectangle
CGContextAddRect(context, CGRectMake(0, 0, 100, 100));
// Draw
CGContextStrokePath(context);
}
此代码用于swift 4.2
func drawRectangle()
{
// Get the Graphics Context
let context = UIGraphicsGetCurrentContext()
// Set the rectangle outerline-width
context?.setLineWidth( 5.0)
// Set the rectangle outerline-colour
UIColor.red.set()
// Create Rectangle
context?.addRect( CGRect(x: 0, y: 0, width: 100, height: 100))
// Draw
context?.strokePath()
}