【问题标题】:Prevent UIButton.imageView from resizing by image防止 UIButton.imageView 按图像调整大小
【发布时间】:2019-03-14 05:48:17
【问题描述】:

我有一个固定高度为 40(约束高度为 40)的UIButton,我通过代码设置图像,该代码是大小为 64x64 的 pdf(矢量图形)。 结果应该是:

我添加了如下图片:

image = [UIImage imageNamed:@"icon-clear"];
[self setImage:image forState:UIControlStateNormal];

我得到的结果是:

imageView 添加了黑色边框,以获得更好的可视化效果。 imageView 的最终尺寸为 64x40

我猜,发生的事情是imageView 获取图像并将其大小调整为 64x64 并通过按钮约束再次缩小到 40,但保留 64 的宽度。

我尝试了多种方法:

self.imageView.frame = CGRect(0,0,32,32);
self.imageView.bounds = CGRect(0,0,32,32);

let aspectRatioConstraint = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.imageView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0];
[self.imageView addConstraint:aspectRatioConstraint];

[self.imageView.widthAnchor constraintEqualToConstant:32];

唯一造成视觉变化的是:

UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();

但最终图像质量很差,我猜是高性能问题。

我只想在多种尺寸的情况下使用 pdf 矢量文件。如何使用UIViewContentModeScaleAspectFit 为按钮 imageView 提供固定大小的图像。

非常感谢!

【问题讨论】:

  • BTN.imageView?.contentMode = .scaleAspectFit
  • 当然,问题是imageView的大小保持在64,所以我有这个距离标题和按钮的左边缘。
  • 您没有提供宽度约束。这就是为什么它采用图像的内部尺寸
  • 是的,我该怎么做?如您所见,通过代码执行此操作没有任何效果,尝试了两种方式。而且 UIButton 没有故事板或我可以设置它的东西。

标签: ios uibutton uiimageview uiimage size


【解决方案1】:

我终于通过在- (void)layoutSubviews {} 方法中添加self.imageView.frame = CGRectMake(4, 4, 32, 32); 解决了这个问题。

所以

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.frame = CGRectMake(4, 4, 32, 32);
}

已经做到了。

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多