如何修复UIButton图片尺寸,使其填满整个按钮区域?
你可以通过调整按钮图片视图的内容模式和按钮内边距来实现图片填满整个按钮区域,修改后的代码如下:
let playButton = UIButton(type: .custom) playButton.backgroundColor = .darkGray // 设置图片(增加可选绑定避免空值问题) if let unmuteImage = UIImage(named: "unmute") { playButton.setImage(unmuteImage, for: .normal) } // 让图片拉伸填满整个图片视图区域 playButton.imageView?.contentMode = .scaleToFill // 移除按钮默认的内边距,让图片贴合按钮边界 playButton.contentEdgeInsets = UIEdgeInsets.zero // 可选:如果不需要高亮状态下图片自动变暗,可添加此设置 playButton.adjustsImageWhenHighlighted = false playButton.frame = CGRect(x: view.frame.width / 2 - 100, y: view.frame.height / 2 - 100, width: 150, height: 150) view.addSubview(playButton)
关键修改说明:
playButton.imageView?.contentMode = .scaleToFill:UIButton的imageView默认内容模式是.center,设置为.scaleToFill会让图片拉伸至完全填满imageView区域;如果想保持图片比例同时填满(可能裁剪边缘),可以改用.scaleAspectFill。playButton.contentEdgeInsets = UIEdgeInsets.zero:UIButton默认带有少量内边距,设置为零能让图片完全贴合按钮的边界。
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

