UIImage Aspect Fill when using drawInRect?
Assuming you have an image called image
, and you want to draw it inside a rectangle targetRect
so that it fills the rect without being distorted, you can use the following code:
let aspect = image.size.width / image.size.height
let rect: CGRect
if targetRect.size.width / aspect > targetRect.size.height {
let height = targetRect.size.width / aspect
rect = CGRect(x: 0, y: (targetRect.size.height - height) / 2,
width: targetRect.size.width, height: height)
} else {
let width = targetRect.size.height * aspect
rect = CGRect(x: (targetRect.size.width - width) / 2, y: 0,
width: width, height: targetRect.size.height)
}
image.draw(in: rect)
Note: this doesn't clip the image, so it will draw outside the edges of the target rect. if you want to clip the image, call CGContextClipToRect(context, rect)
before drawing.
Note also that the core graphics vertical axis is flipped, with zero starting in the bottom-left instead of top-left compared to UIGraphics, so you may need to flip the rect and clipping rect accordingly.
Resize an image with drawInRect while maintaining the aspect ratio like Scale Aspect Fill?
OK, so no ready-made answer... I wrote a swift extension for UIImage, feel free to use it if you need it.
Here it is:
extension UIImage {
func drawInRectAspectFill(rect: CGRect) {
let targetSize = rect.size
if targetSize == .zero {
self.draw(in: rect)
}
let widthRatio = targetSize.width / self.size.width
let heightRatio = targetSize.height / self.size.height
let scalingFactor = max(widthRatio, heightRatio)
let newSize = CGSize(width: self.size.width * scalingFactor,
height: self.size.height * scalingFactor)
UIGraphicsBeginImageContext(targetSize)
let origin = CGPoint(x: (targetSize.width - newSize.width) / 2,
y: (targetSize.height - newSize.height) / 2)
self.draw(in: CGRect(origin: origin, size: newSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
scaledImage?.draw(in: rect)
}
}
So in the example above, you use it like that:
self.pictures[0].drawInRectAspectFill(CGRect(x: 0, y: 0, width: 100, height: 100))
Is it possible to display an image in Core Graphics with an Aspect Fit resize?
You need to do the math yourself. For example:
// desired maximum width/height of your image
UIImage *image = self.imageToDraw;
CGRect imageRect = CGRectMake(10, 10, 42, 42); // desired x/y coords, with maximum width/height
// calculate resize ratio, and apply to rect
CGFloat ratio = MIN(imageRect.size.width / image.size.width, imageRect.size.height / image.size.height);
imageRect.size.width = imageRect.size.width * ratio;
imageRect.size.height = imageRect.size.height * ratio;
// draw the image
CGContextDrawImage(context, imageRect, image.CGImage);
Alternatively, you can embed a UIImageView
as a subview of your view, which gives you easy to use options for this. For similar ease of use but better performance, you can embed a layer containing the image in your view's layer. Either of these approaches would be worthy of a separate question, if you choose to go down that route.
Swift: Draw on image without changing its size (Aspect fill)
This line:
imageView.image?.draw(in: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
Draws the image at the aspect ratio of the screen, but your image is probably not at the same aspect ratio (the ratio of width to height).
I think this might be useful: UIImage Aspect Fit when using drawInRect?
UIimageview drawInRect with aspect to fit mode
If the image has the correct size (i.e., you don't need to scale it to fit into the drawing area), you can use
[image drawAtPoint:CGPointMake(10, 10)];
(or calculate the point differently if you want to center it).
Otherwise, you'll have to calculate a rect with the correct aspect ratio yourself.
Related Topics
iOS with Parse. Pfuser.Currentuser() Not Getting Cached. Returns Nil After App Restart
App Groups Forsecurityapplicationgroupidentifier Returns Nil
What am I Doing Wrong with Allowsfractionalunits on Nsdatecomponentsformatter
How to Add Custom Data to Marker (Google Maps API Swift)
iOS Swift No Such File or Directory in Debug-Iphoneos
Correct Way to Layout Swiftui (Similar to Autolayout)
API to Capture Live Photos in iOS9
How Do View Types Like Text or Image Conform to the View Protocol in Swiftui
Return in Function Without Return Value in Swift
Setcollectionviewlayout' Animation Broken When Also Changing Collection View Frame
Hidden Property Cannot Be Changed Within an Animation Block
Moya/Alamofire - Url Encoded Params with Same Keys
How to Get User Data from Facebook Sdk on iOS
Transition Delegate for Uitabbarcontroller Animation
Swift 3 - Nsfetchrequest Distinct Results
Code Coverage Result Is Not Accurate to Real Coverage in Xcode 7