1
votes

I have multiple sizes of frames, which can be hard coded, or server will decide. I have to select Image from Gallery, which definitely can be of many dimensions.

  1. I am selecting Image from Gallery
  2. I am generating white background UIImage, using code.

    let size = CGSize(width: 424/2, height: 664/2)

      UIGraphicsBeginImageContextWithOptions(size, true, 0)
      UIColor.white.setFill()
      UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
      let background_image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
    

Now, what I want, to make another Image, which keep Leading 20 pixel, Top 20 Pixel, and width and height 20 pixel smaller than original background.

How can I achieve it.

What I tried before coming to StackOverflow.

func mergedImageWith(frontImage:UIImage?, backgroundImage: UIImage?) -> UIImage{

    if (backgroundImage == nil) {
      return frontImage!
    }

    let size = CGSize(width: 424/2, height: 664/2)

    UIGraphicsBeginImageContextWithOptions(size, true, 0)
    UIColor.white.setFill()
    UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let backgroundImage2: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    backgroundImage2?.draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height))

    frontImage?.draw(in: getAspectFillFrame(sizeImageView: size2, sizeImage: (frontImage?.size)!))

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return newImage
  }

here background image is created with aspect fill, but issue is of starting position and complete height and width.

In very simple words. Its like making custom frames and merge them with images(aspect fill) for printing.

can anyone help me out

Thanks.

1

1 Answers

1
votes

Try not ending your image context until all of the images are drawn (I am also including some code that I have working, edited down a bit)

class layeredImageView: UIImageView {
var imageBackground:UIImage!
var imageForeground:UIImage!

UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)

    self.image?.draw(in: self.frame)

    imageBackground.draw(in: CGRect(<rect>)
    imageForeground.draw(in: CGRect(<rect>)

    self.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()


}