iOS:如何在按钮中显示阴影图像?
我的设计师给我发送了一个带有阴影的按钮图像,这很复杂,所以我需要使用按钮图像,而不是自己实现阴影。例如,可点击的红色区域为20*20,整个带阴影的图像为60*60。红色区域不在图像的中心 问题是我想做一个20*20的按钮,它可以显示整个图像 我使用的工具是将UIImageView(大小=60*60)添加到按钮(大小=20*20)中。还有别的办法吗?我认为有一种方法可以只使用图像和按钮,而不使用额外的UIImageViewiOS:如何在按钮中显示阴影图像?,ios,swift,Ios,Swift,我的设计师给我发送了一个带有阴影的按钮图像,这很复杂,所以我需要使用按钮图像,而不是自己实现阴影。例如,可点击的红色区域为20*20,整个带阴影的图像为60*60。红色区域不在图像的中心 问题是我想做一个20*20的按钮,它可以显示整个图像 我使用的工具是将UIImageView(大小=60*60)添加到按钮(大小=20*20)中。还有别的办法吗?我认为有一种方法可以只使用图像和按钮,而不使用额外的UIImageView 这里有一个简单的例子: func createView(x: CGFloa
这里有一个简单的例子:
func createView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
// creating the container view
let view = UIView()
view.frame = CGRect(x: x, y: y, width: width, height: height)
view.backgroundColor = .systemRed
// creating the image view, set the image to the one you want
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: width, height: height)
let image = UIImage(named: "myImage")
imageView.image = image
// creating the button
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: width / 3, height: height / 3)
button.backgroundColor = .systemBlue
// adding a tap response functionality to the button
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
// adding the button and image view to the container
view.addSubview(imageView)
view.addSubview(button)
//adding the container to the superview
self.view.addSubview(view)
}
添加处理按钮点击的方法:
@objc func buttonTapped() {
// all the code for handling a tap goes here
print("button tapped")
}
最后在viewDidLoad()
中调用createView()
:
请务必注意,按钮和图像的x和y值不是指superview的值,而是指容器视图的值
如果要添加阴影图像,它必须包含在Assets.xcsets文件夹中。从那里,您只需将图像的名称更改为图像的名称即可上传。。。。。。。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createView(x: 100, y: 100, width: 60, height: 60)
}