首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

IOS:创建一个带圆角的UIImage或UIImageView

在iOS开发中,创建一个带圆角的UIImage或UIImageView可以通过以下步骤实现:

  1. 首先,创建一个UIImage或UIImageView,并设置其图片内容。
  2. 使用UIBezierPath创建一个圆角矩形,并将其添加到图片的剪辑路径中。
  3. 使用UIGraphicsBeginImageContextWithOptions函数创建一个新的图形上下文,并将其设置为当前上下文。
  4. 将图片绘制到新的图形上下文中,并应用剪辑路径。
  5. 使用UIGraphicsGetImageFromCurrentImageContext函数获取新的图片,并使用UIGraphicsEndImageContext函数结束当前的图形上下文。
  6. 将新的图片设置为UIImageView的image属性。

以下是一个示例代码:

代码语言:swift
复制
func createRoundedImage(image: UIImage, cornerRadius: CGFloat) -> UIImage? {
    let size = image.size
    let rect = CGRect(origin: .zero, size: size)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
    path.addClip()
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

let image = UIImage(named: "example")
let cornerRadius: CGFloat = 20
let roundedImage = createRoundedImage(image: image!, cornerRadius: cornerRadius)
let imageView = UIImageView(image: roundedImage)

在上述示例代码中,我们首先定义了一个名为createRoundedImage的函数,该函数接受一个UIImage对象和一个cornerRadius参数,并返回一个带圆角的UIImage对象。在函数中,我们使用UIBezierPath创建了一个圆角矩形,并将其添加到图片的剪辑路径中。然后,我们使用UIGraphicsBeginImageContextWithOptions函数创建了一个新的图形上下文,并将其设置为当前上下文。接下来,我们将图片绘制到新的图形上下文中,并应用剪辑路径。最后,我们使用UIGraphicsGetImageFromCurrentImageContext函数获取新的图片,并使用UIGraphicsEndImageContext函数结束当前的图形上下文。

在主函数中,我们首先加载了一个名为example的图片,并设置了圆角半径为20。然后,我们调用createRoundedImage函数创建了一个带圆角的UIImage对象,并将其设置为UIImageView的image属性。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券