【问题标题】:How to insert image on UIView?如何在 UIView 上插入图像?
【发布时间】:2018-01-10 05:07:08
【问题描述】:

下面的代码在 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()
    }
}

【问题讨论】:

标签: ios swift image uiview


【解决方案1】:

在视图层添加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)

【讨论】:

    【解决方案2】:

    如果您想在视图中添加图像。请使用以下代码。

    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

    【讨论】:

    • bringSubview() 现在是 BringSubviewToFront()
    【解决方案3】:

    Swift 4上测试

    这个函数应该在 viewDidAppear 中/之后调用来让视图渲染

    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)
    

    【讨论】:

    • 你能告诉我在viddidappear中具体写什么代码吗?
    • @SamBurns 我已经更新了我的答案。 myButtonObject 需要是需要有箭头图像的按钮实例。 my_arrow_image 需要替换为您的箭头图像的名称。
    猜你喜欢
    • 2019-09-18
    • 2021-06-06
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多