How can I set UIButton image, which Image is round shape with border

后端 未结 6 1638
难免孤独
难免孤独 2021-01-24 04:04

How can I set UIButton image, which Image is round shape with border I write related code but image not displaying in proper round shape.. Here is my code..

             


        
6条回答
  •  萌比男神i
    2021-01-24 04:48

    I achieved my desired output the help of @Anbu & also based on the answer of @A.Jam.. Here is my correct code..

    let img = UIImageView(image: #imageLiteral(resourceName: "defaultPhoto"))
            img.image = img.image?.resizeImageWith(newSize: CGSize(width: 25, height: 25))
    
            btnMyProfile.setImage(img.image, for: .normal)
            btnMyProfile.imageView?.contentMode = .scaleAspectFit
            //btnMyProfile.imageView?.setRadius()
            btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)! / 2
            btnMyProfile.imageView?.layer.borderColor = customeMainBlueColor.cgColor
            btnMyProfile.imageView?.layer.borderWidth = 2.0
            btnMyProfile.imageView?.layer.masksToBounds = true
    
    //someFile.swift
    extension UIImage{
    //https://stackoverflow.com/questions/42545955/scale-image-to-smaller-size-in-swift3
        func resizeImageWith(newSize: CGSize) -> UIImage {
    
            let horizontalRatio = newSize.width / size.width
            let verticalRatio = newSize.height / size.height
    
            let ratio = max(horizontalRatio, verticalRatio)
            let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
            UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
            draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
    }
    

提交回复
热议问题