如何在UIView上插入图像?

时间:2018-01-10 05:07:08

标签: ios swift image uiview

下面的代码在UIView上打印一行。我只想知道我要编写的代码,以便能够在视图顶部插入图像。

import UIKit

class draw: UIView {
    var line = UIBezierPath()
    var line1 = UIBezierPath()

    func grapher() {
        line1.move(to: .init(x:0, y: bounds.height / 6))
        line1.addLine(to: .init(x: bounds.width, y: bounds.height / 6))
        UIColor.blue.setStroke()
        line1.lineWidth = 2
        line1.stroke()
    }

    override func draw(_ rect: CGRect) {
        grapher()
    }
}

3 个答案:

答案 0 :(得分:10)

在视图图层上添加UIImage

let myLayer = CALayer()
let myImage = UIImage(named: "star")?.cgImage
myLayer.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
myLayer.contents = myImage
myView.layer.addSublayer(myLayer)

UIImage添加为子视图

let image = UIImage(named: "star")
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
myView.addSubview(imageView)

答案 1 :(得分:0)

如果要在视图上添加图像。请使用以下代码。

    let imageName = "yourImage.png"
    let image = UIImage(named: imageName)
    let imageView = UIImageView(image: image!)
    imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
    self.view.addSubview(imageView)
    //Imageview on Top of View
    self.view.bringSubview(toFront: imageView)

如果您想绘制特定形状,请使用Core Graphics

https://developer.apple.com/documentation/coregraphics

https://cocoacasts.com/drawing-shapes-in-swift-with-paintcode/

https://www.ioscreator.com/tutorials/drawing-shapes-core-graphics-tutorial-ios10

答案 2 :(得分:0)

经过快速4测试

// This function should be called in/after viewDidAppear to let view render
    func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "my_arrow_image") ) {
        let btnSize:CGFloat = 32
        let imageView = UIImageView(image: arrowImage)
        let btnFrame = button.frame
        imageView.frame = CGRect(x: btnFrame.width-btnSize-8, y: btnFrame.height/2 - btnSize/2, width: btnSize, height: btnSize)
        button.addSubview(imageView)
        //Imageview on Top of View
        button.bringSubviewToFront(imageView)
    }

并在viewDidAppear中以这种方式调用

self.addArrowImageToButton(button: myButtonObject)