如何在Button内设置cornerRadius到UIImage?

时间:2015-06-01 18:46:20

标签: ios image swift button cornerradius

我正在使用渐变创建图像,我希望按钮具有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

    }

但无论我尝试什么,都没有角落半径,我该怎么做呢

2 个答案:

答案 0 :(得分:5)

尝试将UIButton的{​​{1}}媒体资源设为clipToBounds

答案 1 :(得分:1)

转到故事板并单击按钮。转到此按钮身份检查器和“用户定义的运行时属性”为关键路径“layer.cornerRadius”为类型“数字”为值“10”我喜欢使用10但你可以玩它!如果您在代码中执行此操作,请在您的行下      button.layer.cornerRadius = 3
添加行
     button.layer.masksToBounds = true