我想实现:
UIImageView
以便显示图像
不符合UIImageView
底线:我想增加UIImageView
的触控区域,而不会将图像拉伸超过一定的尺寸。
是否可以通过故事板?如果没有,谁能告诉我们如何以编程方式进行操作?
我可以通过UIButton
实现类似的功能,并通过故事板设置图片插图,但我找不到UIImageView
的任何内容。
答案 0 :(得分:30)
You can add inset to UIImage
instead of UIImageView
.
Swift 4
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.image = UIImage(named: "example")?.withAlignmentRectInsets(UIEdgeInsets(top: -4, left: 0, bottom: -4, right: 0))
答案 1 :(得分:26)
使用给定here的方法:
Case DATEDIFF(DAY, p.LastLoggedIn, SYSDATETIME())
WHEN 0 THEN 'Online Now'
When >= 1 and <= 7 then 'This Week'
When >= 7 and <= 14 then 'Within Two Weeks'
When >= 14 and <= 21 then 'Within Three Weeks'
END
现在你的插图变成了100-80,即20。
这是一种为UIImageView提供插件的解决方法。欢迎更好的答案。
答案 2 :(得分:20)
看起来你想要一个可触摸的imageView,为什么不使用带图像和imageEdgeInsets的UIButton?
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setFrame:someFrame];
[b setImage:img forState:UIControlStateNormal];
b.imageEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
[b addTarget:self action:@selector(imageClicked:) forControlEvents:UIControlEventTouchUpInside];
答案 3 :(得分:6)
我的代码
Swift4
private lazy var imageView: UIImageView = {
let view = UIImageView()
view.contentMode = .scaleAspectFit
let insetValue: CGFloat = -8
view.image = image.withAlignmentRectInsets(UIEdgeInsets(top: insetValue, left: insetValue, bottom: insetValue, right: insetValue))
return view
}()
答案 4 :(得分:4)
您可以先添加UIView
,然后将UIImageView
添加到UIView
内,填写任意内容,如果您希望手势仅受{ {1}},将UserInteractionEnable设为是,或者如果您希望手势在整体中,则可以将手势添加到整个UIImageView
答案 5 :(得分:3)
尝试了一段时间后,我找到了这个解决方案:
extension UIImage {
func withInset(_ insets: UIEdgeInsets) -> UIImage? {
let cgSize = CGSize(width: self.size.width + insets.left * self.scale + insets.right * self.scale,
height: self.size.height + insets.top * self.scale + insets.bottom * self.scale)
UIGraphicsBeginImageContextWithOptions(cgSize, false, self.scale)
defer { UIGraphicsEndImageContext() }
let origin = CGPoint(x: insets.left * self.scale, y: insets.top * self.scale)
self.draw(at: origin)
return UIGraphicsGetImageFromCurrentImageContext()?.withRenderingMode(self.renderingMode)
}
}
let margin:CGFloat = 16
self.imageView.image = image?.withInset(UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin))
答案 6 :(得分:0)
答案 7 :(得分:0)
一种选择是使用withAlignmentRectInsets
,但不适用于图层边框。
另一种方法是在要为较小的图像使用正插入值的地方使用resizableImage(withCapInsets: resizingMode: .stretch)
。
示例代码:
private func setupQRImageView() -> UIImageView {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.layer.borderColor = Default.imageBorderColor.cgColor
imageView.layer.borderWidth = 4.0
imageView.layer.cornerRadius = 6.0
let imageInset: CGFloat = 8.0
imageView.image = UIImage(named: "QR")?.resizableImage(withCapInsets: UIEdgeInsets(top: imageInset, left: imageInset, bottom: imageInset, right: imageInset), resizingMode: .stretch)
return imageView
}
产生以下结果: