UIView with rounded corners and drop shadow?

前端 未结 30 2980
一整个雨季
一整个雨季 2020-11-22 08:00

I’ve been working on an application for a couple of years and received a simple design request: Round the corners on a UIView and add a drop shadow.To do as given below.

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:30

    Using Swift 4 and Xcode 9, this is a working example of rounding an ImageView with a drop shadow, and a border.

        //set dimensions and position of image (in this case, centered)
        let imageHeight: CGFloat = 150, imageWidth: CGFloat = 150
        let xPosition = (self.view.frame.width / 2) - (imageWidth / 2)
        let yPosition = (self.view.frame.height / 2) - (imageHeight / 2)
    
        //set desired corner radius
        let cornerRadius: CGFloat = 20
    
        //create container for the image
        let imageContainer = UIView(frame: CGRect(x: xPosition, y: yPosition, width: imageWidth, height: imageHeight))
    
        //configure the container
        imageContainer.clipsToBounds = false
        imageContainer.layer.shadowColor = UIColor.black.cgColor
        imageContainer.layer.shadowOpacity = 1
        imageContainer.layer.shadowOffset = CGSize(width: 3.0, height: 3.0)
        imageContainer.layer.shadowRadius = 5
        imageContainer.layer.shadowPath = UIBezierPath(roundedRect: imageContainer.bounds, cornerRadius: cornerRadius).cgPath
    
        //create imageView
        let imageView = UIImageView(frame: imageContainer.bounds)
    
        //configure the imageView
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = cornerRadius
        //add a border (if required)
        imageView.layer.borderColor = UIColor.black.cgColor
        imageView.layer.borderWidth = 1.0
        //set the image
        imageView.image = UIImage(named: "bird")
    
        //add the views to the superview
        view.addSubview(imageContainer)
        imageContainer.addSubview(imageView)
    

    If you want the image to be circular: (and shown without border)

    let cornerRadius = imageWidth / 2
    

提交回复
热议问题