![](/img/trans.png)
[英]How to upload images to azure without losing quality with image data swift
[英]Make UIImage a Circle without Losing quality? (swift)
一旦應用roundImage,圖像就會變得模糊: 將UIImage制作為圓形
extension UIImage
{
func roundImage() -> UIImage
{
let newImage = self.copy() as! UIImage
let cornerRadius = self.size.height/2
UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
let bounds = CGRect(origin: CGPointZero, size: self.size)
UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
newImage.drawInRect(bounds)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage
}
}
試試這個
let image = UIImageView(frame:CGRectMake(0,0,100,100))
我建議您可以使用AlamofireImage( https://github.com/Alamofire/AlamofireImage )
制作圓形圖像或圓形圖像非常容易而又不損失質量。
像這樣:
let image = UIImage(named: "unicorn")!
let radius: CGFloat = 20.0
let roundedImage = image.af_imageWithRoundedCornerRadius(radius)
let circularImage = image.af_imageRoundedIntoCircle()
瞧!
為什么使用bezierpath
? 只需為uiimageview
設置cornerradius
uiimageview
。
如果圖像大於imageview
則必須將image
調整為您的imageview
大小,然后為該uiimageview
設置cornerradius
uiimageview
。
它會工作。 為我工作
替換以下行
UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
與
UIGraphicsBeginImageContextWithOptions(self.size, view.opaque , 0.0)
您的問題是您正在使用標度1,這是最低的“質量”。 將比例尺設置為0將使用設備比例尺,它僅按原樣使用圖像。
注意:類內部的返回該類新實例的函數可以實現為類函數。 這使函數很清楚。 它不操縱現有圖像。 它返回一個新的。
由於您在談論圓圈,因此我也更正了您的代碼,現在它可以對任何圖像進行圓圈繪制並裁剪。 您可能需要將此居中。
extension UIImage {
class func roundImage(image : UIImage) -> UIImage? {
// copy
guard let newImage = image.copy() as? UIImage else {
return nil
}
// start context
UIGraphicsBeginImageContextWithOptions(newImage.size, false, 0.0)
// bounds
let cornerRadius = newImage.size.height / 2
let minDim = min(newImage.size.height, newImage.size.width)
let bounds = CGRect(origin: CGPointZero, size: CGSize(width: minDim, height: minDim))
UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
// new image
newImage.drawInRect(bounds)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// crop
let maybeCrop = UIImage.crop(finalImage, cropRect: bounds)
return maybeCrop
}
class func crop(image: UIImage, cropRect : CGRect) -> UIImage? {
guard let imgRef = CGImageCreateWithImageInRect(image.CGImage, cropRect) else {
return nil
}
return UIImage(CGImage: imgRef)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.