【问题标题】:How to set cornerRadius to UIImage inside a Button?如何在按钮内将cornerRadius设置为UIImage?
【发布时间】:2015-08-15 08:24:34
【问题描述】:

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

    }

但是不管我怎么试都没有圆角半径,我应该怎么试这个

【问题讨论】:

  • 尝试将图层的maskToBounds或按钮的clipToBounds设置为YES
  • 感谢 clipToBounds 工作:)
  • 我将作为答案发布,以便您接受它,这样人们就可以知道它已经回答了。

标签: ios image swift button cornerradius


【解决方案1】:

尝试将UIButtonclipToBounds 属性设置为YES

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2018-10-24
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2012-06-11
      相关资源
      最近更新 更多