Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set a background color in UIimage in swift programming

Tags:

ios

swift

uiimage

I draw an image using drawInRect() method.

My rectangle is size of 120*120 and my image is 100 * 100.

How i can set a background color to my image in swift?

like image 783
Rizwan Shaikh Avatar asked Feb 03 '15 13:02

Rizwan Shaikh


People also ask

How to set image as UIView background in Swift?

How To Set Image As UIView Background. 3.1 Add Image To The Swift Project. First, you should get a jpg or png format image. Right-click the swift project in Xcode left panel, then click Add Files to “project name” menu item in the popup menu list. Select the image in the top file explorer, and select the project name in Add to targets area.

How do I get the background color of a UI image?

Create an instance of UIKit.UIImage, pass the image name as named parameter’s value of UIImage initializer. Create a UIKit.UIColor object with above UIImage instance as initializer parameter. The parameter name is patternImage . let backgroundColor = UIColor(patternImage: uiImage!)

How to add image in Xcode Swift project?

Right-click the swift project in Xcode left panel, then click Add Files to “project name” menu item in the popup menu list. Select the image in the top file explorer, and select the project name in Add to targets area. Then click Add button. Now you can see that the image ( twitter.png in this example ) has been added to the Xcode swift project.

How to create a button with a background image in Xcode?

Create an Xcode swift project. Please refer to How To Create A Swift Project In Xcode. Right-click the project name, then click Add Files to “……” menu item in the popup menu list. Select the images which you want to set as the button’s background image, after that you will see the images in the swift project left panel.


Video Answer


1 Answers

Swift 5, 4

If you need to draw the background of an image, for optimization and decorative purposes, you can draw the image in a specific way:

UIImage(named: "someImage")?.withBackground(color: .white)


Extension

extension UIImage {
  func withBackground(color: UIColor, opaque: Bool = true) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
        
    guard let ctx = UIGraphicsGetCurrentContext(), let image = cgImage else { return self }
    defer { UIGraphicsEndImageContext() }
        
    let rect = CGRect(origin: .zero, size: size)
    ctx.setFillColor(color.cgColor)
    ctx.fill(rect)
    ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
    ctx.draw(image, in: rect)
        
    return UIGraphicsGetImageFromCurrentImageContext() ?? self
  }
}
like image 111
dimpiax Avatar answered Oct 21 '22 16:10

dimpiax