答案 0 :(得分:2)
答案 1 :(得分:2)
我认为这是正确的答案。其他答案并不专注于您提出的问题。
func drawImageOnCanvas(_ useImage: UIImage, canvasSize: CGSize, canvasColor: UIColor ) -> UIImage {
let rect = CGRect(origin: .zero, size: canvasSize)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
// fill the entire image
canvasColor.setFill()
UIRectFill(rect)
// calculate a Rect the size of the image to draw, centered in the canvas rect
let centeredImageRect = CGRect(x: (canvasSize.width - useImage.size.width) / 2,
y: (canvasSize.height - useImage.size.height) / 2,
width: useImage.size.width,
height: useImage.size.height)
// get a drawing context
let context = UIGraphicsGetCurrentContext();
// "cut" a transparent rectanlge in the middle of the "canvas" image
context?.clear(centeredImageRect)
// draw the image into that rect
useImage.draw(in: centeredImageRect)
// get the new "image in the center of a canvas image"
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
答案 2 :(得分:1)
将图像设置如下,只需记住图像的背景色应该清晰。
imageView.image = UIImage(named: "search_image")
imageView.contentMode = .center
答案 3 :(得分:0)
设置图像的宽度/高度固定值。插入具有centerX和centerY约束的背景视图。