Swift 自定义UIView作为背景

Swift 自定义UIView作为背景,swift,uiview,Swift,Uiview,我想使用UIView创建深灰色曲线作为设计 然而,当我试图设置拐角半径时,我认为我做错了,我知道拐角半径仅适用于拐角。也许我不知道实际上还有其他的方法,我想知道是否有一种简单的方法。我这样做的方式是,我在故事板上创建了一个UIView,我创建了一个Cocoa Touch类,它是UIView的子类,并配置了自定义类来继承特性 这里非常感谢您的任何建议 使用拐角半径无法实现该曲线。有两种简单的方法可以满足您的需要:预渲染的UIImage或自定义绘制的CAShapeLayer 选项1:ui图像背景 可

我想使用UIView创建深灰色曲线作为设计

然而,当我试图设置拐角半径时,我认为我做错了,我知道拐角半径仅适用于拐角。也许我不知道实际上还有其他的方法,我想知道是否有一种简单的方法。我这样做的方式是,我在故事板上创建了一个UIView,我创建了一个Cocoa Touch类,它是UIView的子类,并配置了自定义类来继承特性

这里非常感谢您的任何建议


使用
拐角半径
无法实现该曲线。有两种简单的方法可以满足您的需要:预渲染的
UIImage
或自定义绘制的
CAShapeLayer

选项1:ui图像背景

可以在收藏夹图像编辑器中创建背景图像,然后将其设置为居中背景:

// create the UIImageView to display the image
let backgroundImageView = UIImageView()
backgroundImageView.image = UIImage(named: "background")
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(backgroundImageView)

// create constraints to position the UIImageView and apply them
let horizontalConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: backgroundImageView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
view.addConstraints([horizontalConstraint, verticalConstraint])
将其放入
UIViewController
viewdiload()
中,以获得背景信息

你需要为你要瞄准的最大屏幕创建背景图像,并将其添加到你的应用程序资产中。您可以尝试在大小上设置约束,以在每个屏幕上获得所需的大小

这种方法的优点是,如果你想让你的背景更精细,你可以编辑图像

选项2:CAShapeLayer背景

对于您的特定情况(灰色曲线),您可以很容易地使用向量:

// decide on size of ellipse and how to center it
let ellipseWidth:CGFloat = view.frame.width * 7
let ellipseHeight:CGFloat = view.frame.height * 3
let ellipseTop:CGFloat = 100
let ellipseLeft:CGFloat = -ellipseWidth / 2 + view.frame.width / 2

// create the ellipse path
let ellipseOrigin = CGPoint(x:ellipseLeft,y:ellipseTop)
let ellipseSize = CGSize(width: ellipseWidth, height: ellipseHeight)
let ellipsePath = CGPath(ellipseIn: CGRect(origin: ellipseOrigin, size: ellipseSize), transform: nil)

// create the shape layer
let shapeLayer = CAShapeLayer()
shapeLayer.frame = view.frame
shapeLayer.fillColor = UIColor.darkGray.cgColor
shapeLayer.path = ellipsePath
view.layer.addSublayer(shapeLayer)
您可能需要尝试椭圆的比例,以使其看起来恰到好处。7x3看起来与您的示例非常接近

如果你想变得更漂亮,你可以添加其他形状、笔划、渐变等,或者你可以使用
UIBezierPath
来获得准确的曲线

还要注意的是,要使其发挥作用,您需要

import CoreGraphics
在文件的顶部。

考虑一下这个问题