我有image1
,我想将该图像制成圆形,然后将其插入image2
。怎么用swift呢?我无法使用photoshop或其他图片编辑工具执行此操作,因为我的image1
每次都可能不同。
花是image1
。
编辑2:我尝试过的工作方式:
let image2 = UIImage(named: "RedPin")
let newSize = CGSizeMake(image2!.size.width, image2!.size.height)
UIGraphicsBeginImageContext(newSize)
image2!.drawInRect(CGRectMake(0,0,newSize.width,newSize.height))
let imageView: UIImageView = UIImageView(image: image1)
var layer: CALayer = CALayer()
layer = imageView.layer
layer.masksToBounds = true
layer.cornerRadius = CGFloat(65)
UIGraphicsBeginImageContext(imageView.bounds.size)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// decrease top image size
roundedImage.drawInRect(CGRectMake(10,10,45,45), blendMode: .Normal, alpha:1.0)
let createdNewImage = UIGraphicsGetImageFromCurrentImageContext()
然而image1
更像是一个圆边的正方形,一般来说,图像质量较差。以下是上述功能的作用:
编辑3: Toucan库非常适合创建圆形图像(let roundedImage = Toucan(image: newImage).maskWithEllipse().image
),但最终图像版本看起来仍然模糊。为什么?
答案 0 :(得分:1)
我设置了像这样的图像,圆角与你一样的代码。
func UserImageForAnnotation() -> UIImage {
let userPinImg : UIImage = UIImage(named: "pin_user.png")!
UIGraphicsBeginImageContextWithOptions(userPinImg.size, false, 0.0);
userPinImg.drawInRect(CGRect(origin: CGPointZero, size: userPinImg.size))
let roundRect : CGRect = CGRectMake(2, 2, userPinImg.size.width-4, userPinImg.size.width-4)
let myUserImgView = UIImageView(frame: roundRect)
myUserImgView.image = UIImage(named: "pic.png")
// myUserImgView.backgroundColor = UIColor.blackColor()
// myUserImgView.layer.borderColor = UIColor.whiteColor().CGColor
// myUserImgView.layer.borderWidth = 0.5
let layer: CALayer = myUserImgView.layer
layer.masksToBounds = true
layer.cornerRadius = myUserImgView.frame.size.width/2
UIGraphicsBeginImageContextWithOptions(myUserImgView.bounds.size, myUserImgView.opaque, 0.0)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
roundedImage.drawInRect(roundRect)
let resultImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImg
}
在我的图片图片中给出了我想要的确切结果。