Uiimage scale to fit swift. size: Set the UIImage new size .
Uiimage scale to fit swift aspectRatio(image!. The SwiftIU frame modifier uses points. This seems to be a SwiftUI bug. For that reason you can use Font methods to adjust the size. Scale a large image to fit its container using resizing Consider the image Landscape _4 . All other images are assumed to have a scale factor of 1. 3 May 2020 • 2 min read This post presents a method to change the image size of a UIImage without stretching in Swift. scaleAspectFit. circle") . 6, 0. y * self. Currently I have an Image View in my scene that is 100 x 100 (for a profile photo) but when I run the app, the photo Sep 5, 2016 · I have a UIImage with its width much greater than its height. Jun 30, 2015 · Solution for Swift 5 or better: Add this extension to your code. The question here is how can we reduced 12MB to 1MB not based on percentage nor image size (width or height) but based on file size. Mar 10, 2020 · extension UIImage { // Crops an input image (self) to a specified rect func cropToRect(rect: CGRect!) -> UIImage? { // Correct rect size based on the device screen scale let scaledRect = CGRectMake(rect. 6) UIView. png" let image = UIImage(named: imageName) let imageView = UIImageView(image: image!) Finally you'll need to give imageView a frame and add it your view for it to be visible: Jan 2, 2012 · I've an UIImageView with content mode Aspect Fit of size 220x155. setValue(CIImage(image: self), forKey: kCIInputImageKey) if let output = currentFilter. May 31, 2016 · I've an UIImage view that is constrained to all sides of a UIView that has fixed size constraints. minScaleFactor = 0. The image it displays is smaller than the view for large sizes, but larger than the view for small sizes. height' since the font point size probably shouldn't ever need to be larger than the parent's height if that's what you're trying to fit. swift and import SwiftUI at the top. Reduce the image height so it becomes smaller and uses less space. Jun 21, 2016 · Swift 5. height let scaleFactor: CGFloat = scaledToHeight / oldheight let newWidth: CGFloat = sourceImage. Mar 11, 2020 · I am declaring a Button like this : let menuButton = UIButton() After that I am trying to change it's parameter and set his position on the view with the help of LBTATools (a pod) with this funct May 28, 2019 · Sponsor Hacking with Swift and reach the world's largest Swift community! Available from iOS 2. width let scaleFactor = scaledToWidth / oldWidth let newHeight = sourceImage. displayDirection = . size. height / 2) switch axis Mar 29, 2020 · SF Symbol images are maintained as text so that it can be added inside a text as well. Nothing changes. I tried with PDFKIT but the result is not appropriate. width let newHeight = self. width; CGFloat maxHeight = imageView. containerRelativeFrame(. size * scale) The Xcode does not accept and show this message "Binary operator '*' cannot be applied to operands of type 'CGSize' and 'CGFloat" ' – Aug 3, 2019 · You can set weights and sizes: Image(systemName: "checkmark. Best Jul 2, 2019 · I want to show an image in a View, where the image source will vary in size. 1 pdfView. The actual image size will be the image scale multiplied by the image width and height, so it's often nice to pass in a scale of 1. Ask Question Asked 4 years, 1 month ago. Nov 26, 2014 · Just add your UIImageView positioned centered and with all edges snapping to the edges. cgImage Finally, if your like using a view's layer but do need "aspect fit", you'll need to work with a CGImage context, possibly using the UIImage. 0. iOS - Size of Image vs. Aspect Ratio . But I have a question about the property size syntax. /** Resize UIImageView :param: UImage :param: new size CGSize :return: new UImage rezised */ func imageResize (#image:UIImage, sizeChange:CGSize)-> UIImage{ let hasAlpha = true let scale: CGFloat = 0. height Aug 14, 2023 · As you can see in the screenshot, the image inside the button doesn't scale to fit inside it following nor the imagePadding, neither the contentInsets directives of the UIButton. scale cause that's 3 on iPhone 6/7 Plus, but image. copy() else { return nil } return UIImage(cgImage: newCgImage, scale: self. height * scaleFactor let newWidth = oldWidth * scaleFactor UIGraphicsBeginImageContext(CGSize(width:newWidth Oct 9, 2008 · Usually I use this method for my apps (Swift 2. May 5, 2015 · Try this code. Image Resize in swift ios8. Feb 7, 2019 · . My code to convert UIView to UIImage: Nov 7, 2016 · Here, I'm creating a typical graphic (it's full-screen size, on all devices) on the fly func buildImage()->UIImage { let wrapperA:UIView = say, a picture let wrapperB: Discussion. whiteColor(). If you used an image set instead of a data set, you can set the scale of an image by putting them in the corresponding slots: Mar 17, 2021 · The method accept one of two strategies of ContentMode, fit and fill. vga640x480 to specify the image size in my app for processing. Then create a new image of the desired size and fill the background color with UIRectFill. 0) for example, you can set the scale yourself. frame. UIImageをスケーリングする方法. 0 x 480. scaleEffect. Here´s my code: let screenSize: CGRect = UIScreen. width let newHeight = image. height' The initial font size can also be set to 'g. . func imageWithImage (sourceImage:UIImage, scaledToWidth: CGFloat) -> UIImage { let oldWidth = sourceImage. 0))) This will give an UIImage of house with 64. Create an extension. Jun 16, 2021 · When using UIImage fore the image data, the image can be conveniently resized with the following UIImage+Resize extension by providing width and height values as input parameters suing a CGSize structure. thing is u got to find the proportional width and height. But the receipt printing is too small like below mentioned image (Epson TM-T88V printer). I ended up using the suggested method by Mark Kang in the comments under the accepted answer, Image(uiImage: image!). image. Original image is not Dec 5, 2022 · How to resize UIImage with Swift. The size of an image in SwiftUI is specified in point. 0 / CGFloat(M_PI)) } let degreesToRadians: (CGFloat) -> CGFloat = { return $0 / 180. If you multiply the logical size of the image (stored in the size property) by the value in this property, you get the dimensions of the image in pixels. size else { // this will happen if you haven't set the image of the imageView fatalError("Could not get size of image!") } let Thanks for the code everyone! Here is a Swift 3 version. The UIImage view is set to Aspect Fit, but when I set an image from the devices library it appears like the pictures above - the aspect ratio is correct, but only the top corner of the image is shown. 2: class ScaledHeightImageView: UIImageView { override var intrinsicContentSize: CGSize { if let myImage = self. Then, create an extension for UIImage, called aspectFittedToHeight, which will take a newHeight and return a smaller UIImage. image = UIImage(named:"pizza. What I want: A4 page size Image should be centered and scal Jan 14, 2019 · Hi Rob, thanks for your tip. – To make it resize to the container size, we'll use the resizable modifier. system . displayMode = . scale, orientation: self. width let myImageHeight = myImage. This gives exactly what you want. 6. Take a Look here // This extension to save ImageView as UImage extension UIView { func asImage() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer. Swift: UIImage has twice the size. func imageWithImage(image:UIImage,scaledToSize newSize:CGSize)->UIImage{ UIGraphicsBeginImageContext( newSize ) image. let imageName = "person. main. mainScreen(). check if cell is nil? In the context of Swift code, EXC_BAD_INSTRUCTION usually means you’ve hit a compiler trap, that is, an undefined instruction inserted into the code by the compiler because of a bug detected at runtime. Mar 2, 2017 · Try this: First Method: func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image. Sep 27, 2023 · Following extension of UIImage can be used to resize the image: import UIKit import AVFoundation public extension UIImage {/// Resize image while keeping the aspect ratio. 0 imageView. scale let scale = CGAffine Transform (scale X: scale Factor, y: scale Factor) let size = image View. cashOrCredit. Oct 24, 2014 · Swift 5 / Make a non-optional UIImage. borderWidth=1. Image ("fish"). Apr 14, 2016 · I am trying to resize programmatically a UIImageView based on the device screen size, but I can´t make it work. cgContext context. extension UIImage { /// Scales an image to fit within a bounds with a size governed by the passed size. opaque = false // UIGraphicsImageRenderer(). import Foundation import UIKit extension UIImage { func resizeImageTo(size: CGSize) -> UIImage? May 6, 2015 · Image won't fit in scale to fill mode in image view. If you want to keep the aspect ratio, you should use . Apr 9, 2015 · Your answer looks right but this function of mine is actually in a separate helper class than the actual viewcontroller class where I need this UIImage. size remains the same Oct 15, 2017 · I did update of Xcode, cocoa pod, alamofire, alamofireimage today, now I have a red marque on my code about text to image. 1 point is equal to 3 pixel. scale Aspect Fill modes scale the image to fit or fill the space while maintaining the image’s original aspect ratio. ScaleType documentation describes CENTER_CROP as:. Be aware this is a render scaling of the underlying image, it will not be redrawn in the new size, so can become blurry. sessionPreset = . Feb 19, 2018 · You can set autoScales to true. (So the image should keep its width-to-height scale) Jul 3, 2018 · Try to use image size of 24*24 image when you are loading images to UIBARBUTTONIMAGE. Other Dec 1, 2015 · I can't use Aspect Fit (because of white background) or Scale (screws up the aspect ratio). png" let image1 = UIImage(named: imageName) var imageView = UIImageView(frame: CGRectMake(5, 5, 100, 100)) imageView. width * scaleFactor let newHeight: CGFloat = oldheight * scaleFactor UIGraphicsBeginImageContext(CGSize(width: newWidth Jun 30, 2024 · If you do UIImage(data: data, scale: 2. size: Set the UIImage new size Jun 16, 2021 · While UIImage provides convenience instance properties for CGImage and CIImage, converting the UIImage to a Core Video Pixel Buffer can be achieved with the UIImage+CVPixelBuffer extensions. First you create a UIImage from your image file, then create a UIImageView from that: let imageName = "yourImage. struct ContentView: View {var body: some View {Image Sep 23, 2016 · I am having trouble resizing a photo after the camera takes the photo in swift. If your use case requires saving the UIImage after transforming, it will need to be drawn into a new CGContext. width * self. jpg , a photograph with the dimensions 4032 x 3024, showing a water wheel, the surrounding building, and the sky above. You can change the contentMode to fill or fit. bounds この記事では、 SwiftでUIImageのサイズを変更する方法を紹介します。 1. -> how do I get the proper pixel size - cannot use UIScreen. image?. Jun 8, 2019 · Original aspect ratio is 3/2 and the result becomes 1/1 which stretches the image. Fit . translateBy(x: size. 0 to reduce file size, but it doesn't scale the image, but rather applies a lossy compression (i. I use session. IOS Swift UIImage crop to given rect size. – Jul 5, 2024 · When I was searching about cropping an image in Swift, all the results I got were literally editing the image. SwiftUI provides modifiers to scale, clip, and transform images to fit your interface perfectly. Resize UIImageView after Scale Aspect Fit. 0 – see Hacking with Swift tutorial 1. Using storyboard, select the button, then in the size inspect click the dropdown on size just above Content inset. and it helped me a lot. image = UIImage(named: "myImage") guard let imgSize = imageView. outputImage, let Apr 15, 2010 · That's ok not a big problem . png") If that doesnot work, try. fit). import UIKit extension UIImage { var noir: UIImage? { let context = CIContext(options: nil) guard let currentFilter = CIFilter(name: "CIPhotoEffectNoir") else { return nil } currentFilter. As I mentioned, I would like contentInsets configuration to force the image to resize inside the button. Try the button with standard image size which is 32*32. com by checking out this sponsor. I found this useful for a UIImageView that changes the size. like if size is 2048. image provides a block // interface to draw into in a new Feb 3, 2015 · I draw an image using drawInRect() method. extension UIImageView { var mergedToImage: UIImage? { guard let Mar 17, 2018 · I have an image like this: and I'd like to resize this image to a specific width: let's say 200px where the height should also get calculated. Aug 12, 2015 · This code uses UIGraphicsImageRenderer introduced in iOS 10: in my testing it was 10-40% faster than earlier samples with UIGraphicsBeginImageContext (Swift 4 / Xcode 9): extension UIImage { func renderResizedImage (newWidth: CGFloat) -> UIImage { let scale = newWidth / self. I really cannot address a CGImage, ubt UIImage/CIImage have one thing in common - size (for a UIImage) and extent (for a CIImage). In the right interface builder in storyboard try with Aspect fit. When loading image in normal 'UIBUTTON' the image should be compatible with the button. cgContext) } } } // this extension to resize image extension UIImage { func resizeImage(targetSize: CGSize) -> UIImage { let size = self. height let myViewWidth = self. For an extension to UIImage that combines both the resizing and conversion to CVPixelBuffer, also consider the UIImage+Resize+CVPixelbuffer extension. singlePageContinuous pdfView. Feb 15, 2015 · I found a lot solutions here but not for Swift, and I know you can do this with a UIImageView, but in my case i need an programmatically set alpha transparent background image for an UIButton. Nov 27, 2018 · Swift 5. size, CGAffineTransformMakeScale(scaleX, scaleY)) let hasAlpha = true let scale: CGFloat = 0. cell?. It will resize the image to fill the screen. Jul 9, 2015 · It works with me as following, the animation is set to be small then when it start animation it get back to its original size: Swift 2. autoScales = true pdfView. Feb 1, 2013 · If you have the size of the image, why don't you set the frame. The uiimage, scale, and offset will be Bindings since they are parameters to our Sep 29, 2019 · 主にImageのリサイズの時に、FillとかFitとかaspectRatioとか色々あって何を使えばよかったんだっけ?となるので備忘録としてまとめました。そもそも…##Fillとは?枠内いっぱ… A scale to apply to vector images relative to text. 1. Here's a Swift version of Paul Lynch's answer. As the content mode is set to Aspect Fit, the image is scaled with respect to the ratio to fit the UIImageView. size is not given in pixels. func textToImage(drawText text: NSString, Jul 15, 2019 · This will also work for multi-line text to fit the height of its parent. origin. button. Similar solutions… How to find an aspect fit image’s size inside an image view; SwiftUI tips and tricks; All SwiftUI property wrappers explained and compared; How to fill and stroke shapes at the same time Jan 20, 2021 · Scale images of UIImage in UIStackView to fit screen size in iOS app. To calculate the equivalent pixel size for your resized image, scale the size of your image view frame by the scale of your main UIScreen: let scale Factor = UIScreen. imageOrientation) } } May 14, 2012 · Tim's answer is correct, however I wanted to add another suggestion, because in my case there was a simpler solution altogether. Mar 30, 2019 · A couple of observations: Your rawData is floating point, CGFloat, array, but your context isn’t populating it with floating point data, but rather with UInt8 data. extension UIImage { public func coloredImage(color: UIColor) -> UIImage? { return coloredImage(color: color, size: CGSize(width: 1, height: 1)) } public func coloredImage(color: UIColor, size: CGSize) -> UIImage? May 23, 2021 · // A circular crop results in some transparency in the // cropped image, so set opaque to false to ensure the // cropped image does not include a background fill let imageRendererFormat = sourceImage. Aug 22, 2017 · cashImage = UIImage(named: "cash1. Overview. scaledToFit() . If you want a floating point buffer, build a floating point context with CGBitmapInfo. I want to highlight here that a smaller image will scale up to fit or fill the view's bounds, which might cause it to appear pixelated. height; CGFloat viewRatio = maxWidth / maxHeight Nov 15, 2014 · #目的:SwiftでUIImageのsizeを取得する際の注意点をまとめる。objective-cのサンプルを真似してSwiftに書き直すとはまる部分があるので簡単にまとめておきます。 Apr 23, 2019 · Second: using UIImage() func scaleImage(scale: CGFloat) -> UIImage? { if let cgImage = self. Create a new file called Extensions. We aren't specifying a vertical size; more on that in a moment. 0 * CGFloat(M_PI) } // calculate the size of the rotated view's containing Nov 7, 2012 · How to add a UIImage to a CALayer. Size of Oct 21, 2016 · A Swift 4. size doesn't image. Fit content mode attempts to show the whole image by scales the image to fit the view size along one axis, possibly leaving empty space along the other axis. x compatible): // Resize UIImage func resizeImage(image:UIImage, scaleX:CGFloat,scaleY:CGFloat) ->UIImage { let size = CGSizeApplyAffineTransform(image. scaleEffect() works. contents = UIImage(named: "star")?. If you wish to add the image in its own layer, you can do it like this: Nov 12, 2016 · If you just need to scale to the view size with no regard to "aspect fit", you can use it's layer: view. extension UIImage { enum Axis { case horizontal, vertical } func flipped(_ axis: Axis) -> UIImage { let renderer = UIGraphicsImageRenderer(size: size) return renderer. (it's actually half the pixel size). Mar 29, 2021 · That's all three modes that support image scaling. Configuration. ultraLight)) Image(systemName: "checkmark. image { let context = $0. e. cornerRadius = 50;// Corner radius should be half of the height and Mar 14, 2022 · I want to convert a UIImage array to a pdf file. vertical May 29, 2017 · Here is a simple extension to UIImage: //ImageRotation. transform = CGAffineTransformMakeScale(0. I'm dynamically inserting different images in different resolutions, but all larger than the size of the UIImageView. 3, animations: { -> Void in button. fill) where image is of type UIImage because Image type does not expose any size property. In addition to loading images from disk, you can ask the user to supply images from an available camera or photo library using a UIImage Picker Controller object. cgImage Note that the UIImage needs to be converted to a CGImage. The result would guarantee that the whole image is shown. drawInRect() method after making some calculations. render(in: rendererContext. EDIT----Ok, so seeing your comment I propose this: UIImageView *imageView; //so let's say you're image view size is set to the maximum size you want CGFloat maxWidth = imageView. My rectangle is size of 120*120 and my image is 100 * 100. It is also working, But what I except is have to print that converted UIImage with scale to page. aspect fill on right aligned or aspect fill on left aligned. pdfView. size let Sep 15, 2022 · @burnsi I don't want the CustomView's actual frame to change (it needs to stay at 2000x2000) but I want it to scale down to fit in the VStack. // MARK: - Image Scaling. size of the image view to be of this size?. 8 } Let's break that code down: We're saying we want to give this image a frame relative to the horizontal size of its parent. masksToBounds = true imageView. transform = CGAffineTransformMakeScale(1,1) }) Swift 3, 4, 5 Sep 27, 2023 · Resizing UIImage is something that is often needed during the application development. scale); // New CGImage reference based May 6, 2019 · Here, size is a measure of point size, rather than pixel size. The aspectRatio modifier allows you to maintain the aspect ratio of the image. You can also specify an explicit scale factor when initializing an image from a Core Graphics image. The following example shows the three Scale values as applied to a system symbol image, each set against a text view: Feb 12, 2022 · The problem is the absolute positioning of the logo. There is a list of sizes to select from, and this will adjust your image size(if you use system image). How i can set a background color to my image in swift? Jan 24, 2020 · I'm going to need to do cropping - of a CIImage - soon. main. An image There is a great solution here: by olearyj234 . Is there a way to dynamically adjust the size of the image to the width of the containing view or get the screen size ev Oct 28, 2020 · Resize UIImage to fit UIImageView in Swift. Content Mode. maxScaleFactor = 5 pdfView. The example below shows the relative scaling effect. The most common cause of Aug 4, 2015 · Swift 4. How can I actually return a UIIMage from this function? I tried doing a var retImg: UIImage in the fucntion and assigning retImg = image, but that did not work either. The UIView. systemFont(ofSize: 64. 0 but the image. The system renders the image at a relative size based on the available space and configuration options of the image it is scaling. height * scale let newSize This is how you would calculate the new height for an aspectFit ratio: // don't use "image" that's confusing let imageView = UIImageView() // assuming you set the image here imageView. The above code gives a new width and the UIImage will scale to fit the new width, so you just call it like following. Resize UIImage without squashing. Is it correct to use operands between types CGSize and CGFloat? (let size = rect. height * self. contents = UIImage(named: "bg_sunrise")?. Meaning it would literally scale the CustomView and all of its subviews down to fit. CGColor imageView. 0 size. It's work fine, but the problem is that it does not fit to the Strongly inspired by @herme5, refactored into more compact Swift 5/iOS12+ code as follows (fixed vertical flip issue as well): public extension UIImage { /** Returns the flat colorized version of the image, or self when something was wrong - Parameters: - color: The colors to user. Leave it there and click on the right bottom corner as shown below and now go ahead and add 4 constrains to Top, Bottom, Left and Right Edges. extension UIImage { func clone() -> UIImage? { guard let originalCgImage = self. CENTER_CROP. here is my code. This subclass uses center if the image is not larger than the view, otherwise it scales down. scale To Fill value scales the image without regard to the original aspect ratio, which can cause the image to appear distorted. swift import UIKit extension UIImage { public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage { let radiansToDegrees: (CGFloat) -> CGFloat = { return $0 * (180. Jul 17, 2010 · Example right aligned image after scale-to-fit in UIImageView: false myUIImageView. Use this extension to create a solid colored image. SymbolConfiguration(font: . cgImage, let newCgImage = originalCgImage. draw(in: CGRect(x: 0,y: 0,width For Printing, I convert the marked UIView to UIImage and print it. floatComponents and tweak the context parameters accordingly. I was looking to set the UIButton image insets because I didn't realize that I could set the content mode on the button's UIImageView, which would have prevented the need to use UIEdgeInsets and hard-coded values altogether. 9, but visually noticeable at lower values). Also, here is his code in swift 4 and Xcode 9. I'm trying to display it in a UIImageView while keeping the aspect ratio, but the imageview only displays a small part of the image. It could be that the image needs to be resized before uploading or after downloading. 8 or 0. An iPhone 14 Pro screen has a size of 1179 by 2556 pixels. image { let myImageWidth = myImage. You can easily support sarunw. scale, rect. All the newer screens are Retina and have a high pixel density. system(size: 16, weight: . Just remove the line limit and change the last frame to 'height: g. I see two ways: scale the whole resulting image with . I suggest taking a look. 0 // Use scale factor of main screen // Create a Drawing Environment (which will render to a bitmap image, later This code worked great for me to adjust the height of the image loaded from the Web that filled the entire width of the UIImageView. Dec 12, 2021 · I am using Swift's Vision Framework for Deep Learning and want to upload the input image to backend using REST API - for which I am converting my UIImage to MultipartFormData using jpegData() and pngData() function that swift natively offers. Dec 16, 2020 · when loading image from the camera roll (via UIImagePickerController) the scale always seems to be 1. scaleAspectFill will stretch the image to fit into UIImageView. scale Aspect Fit and UIView. I do want to use Aspect Fill and align it in a specific way - i. horizontal) { size, axis in size * 0. 0 which has to be resized to 320 x 480 resolution then the resulting image size should be 722. PDF file page size should be A4. Dec 26, 2014 · Xcode 13, Swift 5. Much like how the . width let ratio Jul 10, 2019 · func scaleImageHeight(sourceImage: UIImage, scaledToHeight: CGFloat) -> UIImage { let oldheight: CGFloat = sourceImage. borderColor = UIColor. Aug 28, 2014 · Following this tutorials you can resize UIImage, In that tutorial described fully . You can add an image to a view's layer simply by using its contents property: myView. The default size is already set when you added the button on the storyboard to the View Controller. Modified 4 years, 1 month ago. Use this type with the image Scale(_:) modifier, or the image Scale environment key, to set the image scale. degrades image quality, introducing artifacts, barely noticeable at values of 0. resizable(). I just needed to set the content mode to Aspect Fill (important) and not set the view's Height constraint, but set Intrinsic size to Placeholder at the bottom of the Size inspector (and type any value in the Height field below). func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{ UIGraphicsBeginImageContextWithOptions May 3, 2020 · Learn how to scale a UIImage to a target size while keeping the aspect ratio the same. I am a beginner with coding. resizable() . The code below works well if you don't want to deal with an optional image when calling your method to make a UIImage. Jul 12, 2014 · You have this code, this code set width and height and save the same position. Aug 29, 2020 · Android's ImageView. 0 // Automatically use scale factor of main screen The UIView. Oct 18, 2021 · I am parsing SVG image file and convert it paths into CAShapeLayer, after that I am adding this CAShapeLayer to UIImage View's layer. Mar 19, 2015 · LeoDabus, I think this is the not right answer but very nice solution for other problems. imageRendererFormat imageRendererFormat. x * self. Oct 31, 2023 · Image(. For example: let resizedImage = UIImage(systemName: "house", withConfiguration: UIImage. animateWithDuration(0. UIImageをスケーリングする方法は、`UIImage`クラスの`scale`メソッドを使用することで実現できます。 Dec 12, 2020 · Add scale in current context and pass image size in UIGraphicsBeginImageContextWithOptions. size, contentMode: . 0 x 1360. 0 Oct 4, 2011 · Best answer Maverick 1st's correctly translated to Swift (working with latest swift 3): . 0 extension that returns an optional UIImage to avoid any potential crashes down the road. cgImage { return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation) } return nil } But I realized that the scale factor in two methods produced conflicting results. width / 2, y: size. func imageResize (imageObj:UIImage, sizeChange:CGSize You can also specify an explicit scale factor when initializing an image from a Core Graphics image. example) . aspectRatio(contentMode: . Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). png") Your aspect fit scaled image is now right Apr 24, 2022 · One possible way would be to create an extension method to UIImage as you started in your sample code. document = createPDF(image: #imageLiteral(resourceName: "Image-1")) pdfView. image { rendererContext in layer. Dec 14, 2015 · extension UIImage { public enum DataUnits: String { case byte, kilobyte, megabyte, gigabyte } func getSizeIn(_ type: DataUnits)-> String { guard let data = self A single image set can provide different versions of an image for different platforms, for different trait environments (compact or regular), and for different scale factors. font(. Jul 25, 2015 · For Swift 3. Jun 28, 2016 · @sethmr - Yep, you can use a quality setting below 1. layer. The best way is you try both solution in the code to see the final result. Apr 30, 2023 · In order to get the right area, I had to consider the screen size and pixel density of the iPhone 14. rqwhgnjdnzayksryjrawsuwkchsuocdhfhmmuxsvycasoapvevamm