如何快速将图像设置为具有背景色的imageview中心

时间:2018-09-21 11:43:00

标签: ios xcode

我的图片为30x30。我想将此图像放到另一个500x500图像的中心,并且要像下面的示例一样为500x500图像定义背景。有什么办法可以做到这一点?谢谢。

İmages

4 个答案:

答案 0 :(得分:2)

您可以借助情节提要来完成此操作,如下图所示。enter image description here

,输出为:

enter image description here

答案 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约束的背景视图。