How to make imageview with different shape in swif

2019-02-11 08:46发布

enter image description here

I want to change the normal ios imageview to this below image shape(Like arc)

1条回答
对你真心纯属浪费
2楼-- · 2019-02-11 09:42

You can use this to design the shape as per your requirement, you can add extra lines to the path incase you need to modify the bezier path. Create a custom UIImageView class and subclass the image view in storyboard to your custom class.

import UIKit

class customImageView: UIImageView {


    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    //    override func drawRect(rect: CGRect)
    //    {
    //
    //
    //    }


    override func setNeedsLayout() {
        let path = UIBezierPath()
        path.moveToPoint(CGPoint(x: self.frame.size.width/2, y: self.frame.size.height))
        path.addLineToPoint(CGPoint(x: self.frame.size.width, y: self.frame.size.height/2))
        path.addLineToPoint(CGPoint(x: self.frame.size.width/2, y: 0))
        path.addArcWithCenter(CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2), radius: self.frame.size.width/2, startAngle:-CGFloat(M_PI_2), endAngle: CGFloat(M_PI_2), clockwise: false)

        path.moveToPoint(CGPoint(x: self.frame.size.width/2, y: self.frame.size.height))
        path.closePath()
        UIColor.redColor().setFill()
        path.stroke()
        path.bezierPathByReversingPath()
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.bounds
        shapeLayer.path = path.CGPath
        shapeLayer.fillColor = UIColor.redColor().CGColor
        self.layer.mask = shapeLayer;
        self.layer.masksToBounds = true;
    }

}

If you want to add the image through code kindly use it like this

 func shapeImage()
    {
        let customImgView = customImageView()
        customImgView.image = UIImage(named: "Image")
        customImgView.frame = CGRectMake(0, 0, 250, 250)

        self.view.addSubview(customImgView)
    }

This is the actual image on left hand side and the image after shaping as per your requirement in the simulator on the right hand side

enter image description here

查看更多
登录 后发表回答