如何在Swift中正确设置imageView在sqContacts中?

时间:2014-08-30 23:46:17

标签: ios swift uiimageview xcode6

我希望将图片显示到imageView中,就像图片联系人一样(在一个圆圈中)但是当我尝试显示这个时,imageView会重新调整他的大小,这在圆圈中无法正确显示..

 image.layer.borderWidth=1.0
 image.layer.masksToBounds = false
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.clipsToBounds = true

我想要这样的节目: enter image description here

但我得到了这个: enter image description here

如何将该图像调整为UIImageView大小以显示为圆圈?

谢谢!

19 个答案:

答案 0 :(得分:35)

frame使用的image尺寸是多少?如果我将框架设置为正方形,我可以得到一个完美的圆圈。

let image = UIImageView(frame: CGRectMake(0, 0, 100, 100))

答案 1 :(得分:16)

快速 简单 解决方案。

如何掩盖 UIImage进行循环而不使用Swift进行裁剪。

extension UIImageView {
  public func maskCircle(anyImage: UIImage) {
    self.contentMode = UIViewContentMode.ScaleAspectFill
    self.layer.cornerRadius = self.frame.height / 2
    self.layer.masksToBounds = false
    self.clipsToBounds = true

   // make square(* must to make circle), 
   // resize(reduce the kilobyte) and 
   // fix rotation.
   self.image = anyImage
  }
}

如何致电:

let anyAvatarImage:UIImage = UIImage(named: "avatar")!
avatarImageView.maskCircle(anyAvatarImage)

答案 2 :(得分:5)

这就是你所需要的......

package;


typedef Constructible = {
  public function new():Void;
}


// Dialog base class
// Every dialog in my application will derive from this
class Dialog
{
    public function new()
    {
        trace("dialog");
    }
}


class SuperDialog extends Dialog
{
    public function new()
    {
        super();
        trace("super dialog");
    }
}

// A simple class that tries to instantiate a specialized dialog, like TestDialog 

class SomeAppClass
{
    public function new() 
    {
        var dialog = create(Dialog);
        var superDialog = create(SuperDialog);
    }

    @:generic
    public static function create<T:(Constructible,Dialog)>(type:Class<T>):T
    {
        return new T();
    }
}

class Test {
  static public function main() {
    new SomeAppClass();
  }
}

答案 3 :(得分:5)

我建议您将图像文件设置为完美的正方形。这几乎可以在任何照片编辑程序中完成。之后,这应该在viewDidLoad中工作。相信这个video

image.layer.cornerRadius = image.frame.size.width/2
image.clipsToBounds = true

答案 4 :(得分:4)

如果您使用Autolayout,请创建自定义圈UIImageView并在layoutSubviews帮助下创建圈子。

unique(pib[, list(quatley, year, sum.quatley)])
   quatley year sum.quatley
1:       1 2010     1193503
2:       2 2010     1303736
3:       3 2010     1388608
4:       1 2011     1365789
5:       2 2011     1487798
6:       3 2011     1522795

答案 5 :(得分:2)

reviewerImage.layer.cornerRadius = reviewerImage.frame.size.width / 2;
reviewerImage.clipsToBounds = true

答案 6 :(得分:2)

我在修改视图时修复了它:

  1. 转到 Main.storyboard
  2. 点击您的图片
  3. 查看 - &gt;模式 - &gt; Aspect Fill
  4. 完美无缺

答案 7 :(得分:1)

试试这个。 swift 代码

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    perform(#selector(self.setCircleForImage(_:)), with: pickedImage, afterDelay: 0)
}


 @objc func setCircleForImage(_ imageView : UIImageView){
    imageView.layer.cornerRadius = pickedImage.frame.size.width/2
    imageView.clipsToBounds = true
}

答案 8 :(得分:1)

如果您使用UIViewController,请使用锚点进行操作。关键是在layer.cornerRadius中设置imageView的viewWillLayoutSubviews,如下所示:

override func viewWillLayoutSubviews(){
    imageView.layer.cornerRadius = imageView.frame.size.width / 2
}

还要确保heightAnchorwidthAnchor的大小相同。在下面的示例中,它们都是100

代码:

let imageView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.layer.borderWidth = 1.0
    imageView.clipsToBounds = true
    imageView.layer.borderColor = UIColor.white.cgColor
    return imageView
}()


override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(imageView)

    imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true

    imageView.image = UIImage(named: "pizzaImage")
}

override func viewWillLayoutSubviews() {
    imageView.layer.cornerRadius = imageView.frame.size.width / 2
}

如果您使用CollectionView Celllayer.cornerRadius中设置了imageView的layoutSubviews()

override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(imageView)

    imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 50).isActive = true

    imageView.image = UIImage(named: "pizzaImage")

}

override func layoutSubviews() {
    super.layoutSubviews() // call super.layoutSubviews()
    imageView.layer.cornerRadius = imageView.frame.size.width / 2
}

答案 9 :(得分:1)

// MARK:ImageView扩展程序可以制作圆形框架

@IBDesignable扩展UIImageView {

@IBInspectable var masksToBounds: Bool {
    set {
        layer.masksToBounds = newValue
    }
    get {
        return layer.masksToBounds
    }
}

@IBInspectable var borderWidth: CGFloat {
    set {
        layer.borderWidth = newValue
    }
    get {
        return layer.borderWidth
    }
}

@IBInspectable var cornerRadius: CGFloat {
    set {
        layer.cornerRadius = newValue
    }
    get {
        return layer.cornerRadius
    }
}

@IBInspectable var borderColor: UIColor? {
    set {
        guard let uiColor = newValue else { return }
        layer.borderColor = uiColor.cgColor
    }
    get {
        guard let color = layer.borderColor else { return nil }
        return UIColor(cgColor: color)
    }
}

}

答案 10 :(得分:1)

您可以将此文件扩展名添加到您的项目中,并且不要忘记使图像成为平方“宽度=高度”,并且可以通过提供图像宽度和纵横比来授予它(1:1)

import Foundation
import UIKit


extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!)
            return color
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
    
}

然后,您将在单元格或视图控制器中或任何使用图像的地方写以下

imageViewCountryImage.cornerRadius = imageViewCountryImage.frame.height / 2

您会发现您的图片非常超圆

答案 11 :(得分:0)

我发现你的图像视图的宽度和高度在除以2时必须返回一个偶数来得到一个完美的圆,例如

let image = UIImageView(frame: CGRectMake(0, 0, 120, 120))

它不应该是这样的     let image = UIImageView(frame:CGRectMake(0,0,130,130))

答案 12 :(得分:0)

这对我也有用。要获得完美的圆形结果,请在宽度和高度上使用相同的尺寸。比如image.frame = CGRect(0,0,200, 200)

对于非完美圆形,宽度和高度不应与下面的代码相同。

 image.frame = CGRect(0,0,200, 160)
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.layer.masksToBounds = false
 image.layer.clipsToBounds = true
 image.contentMode = .scaleAspectFill

答案 13 :(得分:0)

我有类似的结果(更多的是椭圆形而不是圆形)。事实证明,我在UIImageView上设置的约束将其强制为椭圆形而不是圆形。在确定之后,上述解决方案起作用。

答案 14 :(得分:0)

使用此代码进行图像循环

     self.layoutIfNeeded()
     self.imageView.layer.cornerRadius = 
     self.imageView.frame.width/2
     self.imageView.layer.masksToBounds = true

答案 15 :(得分:0)

尝试一下对我有用,

imageView 的宽度和高度设置为相同。

快速

**In app.routing.ts**

  routes: Routes = [
        {
            path: '',
            component: LoginComponent,
            children: [
              {
                path: 'login',
                canActivate: [AuthGuard]
              }
            ]
        },
        {
             path: '', component: WebLayoutComponent,canActivate: [AuthGuard],
             children: [
                { path: '',redirectTo: 'dashboard', component: dashboardComponent, canActivate: [AuthGuard] },
                { path: 'dashboard', component: dashboardComponent,canActivate: [AuthGuard]},
                { path: 'matchedroute1', component: matchedRouteComponent, canActivate: [AuthGuard]},
                { path: 'matchedroute2', component: matchedRouteComponent, canActivate: [AuthGuard]}
             ]
        }
    ]
**In auth.guard.ts**

        import { Router, ActivatedRoute } from '@angular/router';
    import { routes } from '../app.routing';

    @Injectable()
    export class AuthGuard  {
       constructor(private router: Router,private activatedRoute: ActivatedRoute) { 

       }

      canActivate(routeerstate?: any) {
       let url = routeerstate._routerState.url; // this url is unactivated route which the user is trying to enter;
      let validRoutes = routes;
      url = url.replace(/\//g,"");
      const isRouteValid = validRoutes.findIndex((item) => item.path === url) > -1 ? true : false; 
      if(isRouteValid){
         if(this.isLoggedIn()) {
          if(url === 'login'){
            this.router.navigate(['dashboard']);
          } else {
            return true;
          }
         } else {
            this.router.navigate(['login']);
         }
       } else { 
        if(this.isLoggedIn()) { // not valid route and logged In
            this.router.navigate(['dashboard']);
        }
       }

      }

      isLoggedIn() {
        //write your authentication and authorization code and return true or false
      }
    }

**In app.component.html**

<router-outlet></router-outlet>

**In webLayout.component.html**

<div class= "container">
    <app-header></app-header>
    <app-ad></app-ad>
</div>
<router-outlet ></router-outlet>
<footer-container></footer-container>

屏幕截图 enter image description here

目标C

imageview?.layer.cornerRadius = (imageview?.frame.size.width ?? 0.0) / 2     
imageview?.clipsToBounds = true
imageview?.layer.borderWidth = 3.0
imageview?.layer.borderColor = UIColor.white.cgColor

希望这对某些人有帮助。

答案 16 :(得分:0)

此扩展程序确实对我有效(包括4+)

ctm-core

然后简单地称呼为

extension UIImageView {
    func roundedImage() {
        self.layer.cornerRadius = (self.frame.size.width) / 2;
        self.clipsToBounds = true
        self.layer.borderWidth = 3.0
        self.layer.borderColor = UIColor.white.cgColor
    }
}

答案 17 :(得分:0)

您需要确保高度和宽度与图像/视图相同。例如100宽度和100高度尺寸。

答案 18 :(得分:0)

您可以将此扩展添加到您的代码中

import Foundation
import UIKit


extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!)
            return color
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
    
}