文本图像非常小,尺寸为17px x 10px
可以在MacOS中完美放大
let width = scale * image.size.width * kScale
let height = scale * image.size.height * kScale
super.init(frame: NSRect(x: 0, y: 0, width: width, height: height))
self.makeConstraints(width: width, height: height)
self.drawBlock = { (context, bounds) in
image.draw(in: bounds)
}
并重新绘制:
override func draw(_ dirtyRect: NSRect) {
// Fill with optional background color.
if let color = bgColor {
color.set()
bounds.fill(using: .sourceOver)
}
// Draw with optional draw block.
if let block = drawBlock {
let context = NSGraphicsContext.current!.cgContext
block(context, bounds)
}
super.draw(dirtyRect)
}
我尝试使用以下两种方法在iOS中进行同一操作,但图像质量低下:
func imageScaledToSize(image: UIImage, size : CGSize) -> UIImage{
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let imageRect = CGRect(origin: .zero, size: size)
image.draw(in: imageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {
let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let context = UIGraphicsGetCurrentContext()
// Set the quality level to use when rescaling
context!.interpolationQuality = CGInterpolationQuality.high
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height)
context!.concatenate(flipVertical)
// Draw into the context; this scales the image
context?.draw(image.cgImage!, in: CGRect(x: 0.0,y: 0.0, width: newRect.width, height: newRect.height))
let newImageRef = context!.makeImage()! as CGImage
let newImage = UIImage(cgImage: newImageRef)
// Get the resized image from the context and a UIImage
UIGraphicsEndImageContext()
return newImage
}
如何调整尺寸以获得更好的图像?谢谢。
在绘制到上下文之前,您需要将上下文插值设置为无:
extension UIImage {
func resized(toWidth width: CGFloat, interpolationQuality: CGInterpolationQuality = .none) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.interpolationQuality = interpolationQuality
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
对于iOS 10或更高版本,您可以按以下方式使用UIGraphicsImageRenderer
:
extension UIImage {
func resized(toWidth width: CGFloat, interpolationQuality: CGInterpolationQuality = .none) -> UIImage? {
let canvas = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
return UIGraphicsImageRenderer(size: canvas, format: imageRendererFormat).image { context in
context.cgContext.interpolationQuality = interpolationQuality
draw(in: CGRect(origin: .zero, size: canvas))
}
}
}