[英]How to insert image on UIView?
The code below prints a line on a UIView.下面的代码在 UIView 上打印一行。 I just want to know the code that I would write to be able to insert an image on top of the view.
我只想知道为了在视图顶部插入图像而编写的代码。
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()
}
}
Add UIImage
on the view layer在视图层添加
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)
Add UIImage
as a subView将
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)
If you want to add image on view.如果要在视图中添加图像。 Please use below code.
请使用下面的代码。
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)
If you want to draw specific shape then go with Core Graphics
如果要绘制特定形状,请使用
Core Graphics
https://developer.apple.com/documentation/coregraphics https://developer.apple.com/documentation/coregraphics
https://cocoacasts.com/drawing-shapes-in-swift-with-paintcode/ https://cocoacasts.com/drawing-shapes-in-swift-with-paintcode/
https://www.ioscreator.com/tutorials/drawing-shapes-core-graphics-tutorial-ios10 https://www.ioscreator.com/tutorials/drawing-shapes-core-graphics-tutorial-ios10
Tested on Swift 4
在
Swift 4
上测试
This function should be called in/after viewDidAppear to let view render应在 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)
}
and call it this way in viewDidAppear并在 viewDidAppear 中这样调用
self.addArrowImageToButton(button: myButtonObject)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.