Yak*_* M. 6 uibutton uikit ios swift
我正在研究 的子类UIButton,让\xe2\x80\x99s 称之为MyButton。在大多数情况下,该子类的按钮将同时具有图像和标题。
MyButton我在配置\xe2\x80\x99s大小时遇到问题imageView。目标是限制图像的大小,以便调整较大图像的大小并适合 32 x 32 的正方形。
出于测试目的,我添加了一个 128 x 128 像素的图像,并将imageView\xe2\x80\x99s设置backgroundColor为green。
下面是我添加图像时按钮的样子。和imageView它的image尺寸均为 128 x 128 像素。

在我覆盖MyButton\xe2\x80\x99sintrinsicContentSize并将CGSize(width: 160, height: 50)按钮 \xe2\x80\x99s imageView\xe2\x80\x99s设置contentMode为后.scaleAspectFit,imageView调整大小,但仅在高度 \xe2\x80\x94it\xe2\x80\x99s 仍然是 128 像素宽,这会导致按钮\xe2\x80\x99s 标题被截断。

我\xe2\x80\x99已经看过很多关于如何image使用. 这不是我想要的,因为在所有这些文章中imageViewimageEdgeInsetsimageView保留其大小,只在图像周围添加填充。
更改imageView\xe2\x80\x99sframe或bounds不会产生任何结果。
关于如何调整按钮大小的任何想法\xe2\x80\x99simageView?
let customButtonImage = MyButton.currentImage
Run Code Online (Sandbox Code Playgroud)
现在您已经使用@jay 的扩展来调整按钮图像的大小来调整图像大小
let newimage = customButtonImage. resizedImage(size:requiredSize)
Run Code Online (Sandbox Code Playgroud)
将图像重置为按钮
self.setImage(newimage, for: .normal) //normal or what state your want
Run Code Online (Sandbox Code Playgroud)
@jays 扩展
extension UIImage
{
func resizedImage(Size sizeImage: CGSize) -> UIImage?
{
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: sizeImage.width, height: sizeImage.height))
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
self.draw(in: frame)
let resizedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.withRenderingMode(.alwaysOriginal)
return resizedImage
}
}
Run Code Online (Sandbox Code Playgroud)
您可以调整图像大小,然后将广告添加到按钮的图像上。您可以在下面找到调整图像大小的代码。
extension UIImage
{
func resizedImage(Size sizeImage: CGSize) -> UIImage?
{
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: sizeImage.width, height: sizeImage.height))
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
self.draw(in: frame)
let resizedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.withRenderingMode(.alwaysOriginal)
return resizedImage
}
}
Run Code Online (Sandbox Code Playgroud)
按钮 ui 扩展。
@IBInspectable var sizeImage: CGSize {
get {
return self.imageView?.image?.size ?? CGSize.zero
}
set {
if let image = self.imageView?.image {
let imgUpdate = image.resizedImage(Size: newValue)
self.setImage(imgUpdate, for: .normal)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8264 次 |
| 最近记录: |