[英]How do I make an UIImage/-View with rounded corners CGRect (Swift)
如何在 Swift iOS Playground 上制作带圆角的 UIImageView?
在里面它需要填充一种颜色。
let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
imageView.backgroundColor = UIColor.redColor()
imageView.layer.cornerRadius = 8.0
imageView.clipsToBounds = true
结果:
对于 swift 中的圆形图像框架,它对我有用的是:
self.profileImageView.image = UIImage(named:"profileUser")
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
self.profileImageView.clipsToBounds = true
添加阴影:
self.profileImageView.layer.masksToBounds = NO;
self.profileImageView.layer.cornerRadius = 8;
self.profileImageView.shadowOffset = CGSizeMake(5.0, 5.0);
self.profileImageView.shadowRadius = 5;
self.profileImageView.shadowOpacity = 0.5;
试试这个,它对我有用。
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
self.profileImageView.clipsToBounds = true
我厌倦了为每个 UIView 编写设置半径和掩码来绑定。 所以我为 UIView 做了以下扩展。 应该适用于每个 UIView 子类,尽管我还没有测试过。 当然,可以针对您使用的特定视图缩小扩展范围。
extension UIView {
func setRadius(radius: CGFloat? = nil) {
self.layer.cornerRadius = radius ?? self.frame.width / 2;
self.layer.masksToBounds = true;
}
}
如果您不传递任何特定值,它将默认为视图的半宽。
如果您想有一个选项来舍入每个UIImageView
,您可以将此代码复制到您的项目中,而不必忘记检查clip to bounds
并将其值设置为true
import UIKit
@IBDesignable
extension UIImageView
{
private struct AssociatedKey
{
static var rounded = "UIImageView.rounded"
}
@IBInspectable var rounded: Bool
{
get
{
if let rounded = objc_getAssociatedObject(self, &AssociatedKey.rounded) as? Bool
{
return rounded
}
else
{
return false
}
}
set
{
objc_setAssociatedObject(self, &AssociatedKey.rounded, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
layer.cornerRadius = CGFloat(newValue ? 1.0 : 0.0)*min(bounds.width, bounds.height)/2
}
}
}
斯威夫特 5.0:
我个人的偏好是为像这样的特定更改提供一个额外的 swift 文件。 然后我要做的是创建一个类,例如“RoundCorner”,它是我想在这种情况下更改为 View 元素的元素的子类。 然后我覆盖了各个设置。
class RoundCorner: UIView {
override func draw(_ rect: CGRect) {
self.layer.cornerRadius = 10 // change this number to get the corners you want
self.layer.masksToBounds = true
}
}
之后,您只需选择要更改的元素,并将自定义类设置为我们之前创建的类。
在身份检查器的用户定义的运行时属性部分设置layer.cornerRadius = 10甚至适用于可重复元素,如表格单元格。
在 Swift 4 中,你可以很容易地做到这一点:
yourUIImage.layer.cornerRadius = 10 // Set it how you prefer
yourUIImage.layer.masksToBounds = true
如果您使用相当长的矩形图像,例如用于您应用程序中的特色内容部分或其他任何内容,请确保将Content Mode
设置为“ Scale To Fit
,否则角会以某种方式变圆但会被严重切割并且不会是一个完美的圆角,而是一个圆角,然后在它夹住的地方进行锐利的切割。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.