如何在 Button 内将 cornerRadius 设置为 UIImage?

How to set cornerRadius to UIImage inside a Button?

我正在创建带渐变的图像,我希望按钮具有 cornerRadius

button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        button.frame = CGRectMake(self.view.frame.size.width/2 - button.frame.size.width, 100, 250, 50)
        button.layer.cornerRadius = 3
        button.setTitle("ViewThree", forState: UIControlState.Normal)
        button.addTarget(self, action: "ViewControllerAction:", forControlEvents: UIControlEvents.TouchUpInside)
        button.setBackgroundImage(getImageWithGradient(UIColor(netHex:0x2d72cf).CGColor, bottom: UIColor(netHex:0x2d72cf).CGColor, size: CGSize(width: button.bounds.width, height: button.bounds.height), frame: button.bounds), forState: UIControlState.Normal)

func getImageWithGradient(top: CGColor, bottom: CGColor, size: CGSize, frame: CGRect) -> UIImage{
        var image = UIImage()
        UIGraphicsBeginImageContext(frame.size)
        var context = UIGraphicsGetCurrentContext()

        image.drawAtPoint(CGPointMake(0, 0))

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations:[CGFloat] = [0.0, 1.0]


        let gradient = CGGradientCreateWithColors(colorSpace,
            [top, bottom], locations)

        let startPoint = CGPointMake(frame.size.width / 2, 0)
        let endPoint = CGPointMake(frame.size.width / 2, frame.size.height)
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)

        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image

    }

但是无论我怎么试都没有角半径,我应该怎么试这个

尝试将 UIButtonclipToBounds 属性 设置为 YES

转到故事板并单击按钮。转到此按钮身份检查器和 "User Defined Runtime Attributes" 键路径 "layer.cornerRadius" 类型 "Number" 值“10” 我喜欢使用 10 但你可以玩弄它!如果您在代码中执行此操作,请在您的行下
button.layer.cornerRadius = 3
添加行
button.layer.masksToBounds = 真