如何在UIView上插入图像?

Sam*_*rns 2 image uiview ios swift

下面的代码在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()
    }
}
Run Code Online (Sandbox Code Playgroud)

dah*_*boy 11

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)
Run Code Online (Sandbox Code Playgroud)

添加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)
Run Code Online (Sandbox Code Playgroud)


Ren*_*iya 8

如果要在视图中添加图像。请使用下面的代码。

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)
Run Code Online (Sandbox Code Playgroud)

如果你想绘制特定的形状然后去 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