UIView+CornerRadius.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // UIView+CornerRadius.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/1/17.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import UIKit
  9. extension UIView {
  10. @IBInspectable var cornerRadius: CGFloat {
  11. get { return layer.cornerRadius }
  12. set {
  13. layer.cornerRadius = newValue
  14. layer.masksToBounds = newValue > 0
  15. }
  16. }
  17. @IBInspectable var borderWidth: CGFloat {
  18. get { return layer.borderWidth }
  19. set { layer.borderWidth = newValue }
  20. }
  21. @IBInspectable var borderColor: UIColor {
  22. get { return UIColor(cgColor: layer.borderColor!) }
  23. set { layer.borderColor = newValue.cgColor }
  24. }
  25. func setShadow(shadowOpacity:Float = 0.1,
  26. shadowRadius:CGFloat = kCornerRadius,
  27. shadowOffset:CGSize = .zero,
  28. shadowColor:CGColor = UIColor.db_black.cgColor
  29. ) {
  30. layer.masksToBounds = false
  31. layer.contentsScale = UIScreen.main.scale
  32. layer.shadowOpacity = shadowOpacity
  33. layer.shadowRadius = shadowRadius
  34. layer.shadowOffset = shadowOffset
  35. layer.shadowColor = shadowColor
  36. layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: shadowRadius).cgPath
  37. //设置缓存
  38. layer.shouldRasterize = true
  39. //设置抗锯齿边缘
  40. layer.rasterizationScale = UIScreen.main.scale
  41. }
  42. func clipRectCorner(direction: UIRectCorner,cornerRadius: CGFloat) {
  43. let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
  44. let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize)
  45. let maskLayer = CAShapeLayer()
  46. maskLayer.frame = bounds
  47. maskLayer.path = maskPath.cgPath
  48. layer.mask = maskLayer
  49. }
  50. }