Swift--Label高效切圆

上代码:

func circleImageWithString(string: String, frame: CGRect, textFont: CGFloat, backgroundColor: UIColor, textColor: UIColor) -> UIImage {
  let titleLabel = UILabel(frame: CGRectMake(0,0,frame.size.width * 3,frame.size.height * 3))
  titleLabel.backgroundColor = UIColor.blueColor()
  titleLabel.text = string
  titleLabel.font = UIFont.systemFontOfSize(textFont * 3)
  titleLabel.backgroundColor = backgroundColor
  titleLabel.textAlignment = .Center
  titleLabel.textColor = textColor
  UIGraphicsBeginImageContext(titleLabel.frame.size)
  let context: CGContextRef = UIGraphicsGetCurrentContext()!
  CGContextSetLineWidth(context, 0)
  CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
  let rect = CGRectMake(0, 0, titleLabel.frame.size.width, titleLabel.frame.size.height)
  CGContextAddEllipseInRect(context, rect)
  CGContextClip(context)
  titleLabel.layer.drawInContext(context)
  CGContextAddEllipseInRect(context, rect)
  CGContextStrokePath(context)
  let newImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return newImage
}

你可能感兴趣的:(Swift--Label高效切圆)