按钮中的图像无法加载,我只得到一个蓝色方块

时间:2016-06-16 08:41:23

标签: ios swift uibutton uiimage

我正在尝试向屏幕添加按钮并以编程方式对其进行编辑,但大多数编辑都没有响应。

这是按钮代码:

@IBOutlet weak var buttonTest: UIButton!

let screen = UIScreen.mainScreen().bounds

let buttonImg = ResizeImage(UIImage(named: "Blokker")!, targetSize: CGSize(width: 50, height: 50))
    buttonTest.frame = CGRect(x: 0, y: screen.height - 300, width: screen.width * 0.5, height: screen.width * 0.5)
    buttonTest.setImage(buttonImg, forState: .Normal)
    buttonTest.setTitle("Test", forState: .Normal)
    buttonTest.imageView?.contentMode = .ScaleAspectFit
    view.addSubview(buttonTest)

ResizeImage功能正常工作,我已经在其他视图控制器中使用过它。这个代码在下面引用。 buttonTest.frame方法不起作用,按钮将始终保持在同一位置而不编辑大小。图像也不会加载,在图像所在的位置,我只能看到蓝色方块。

有谁知道如何解决这个问题?提前致谢!

ResizeImage功能:

func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
    } else {
        newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRectMake(0, 0, newSize.width, newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.drawInRect(rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

3 个答案:

答案 0 :(得分:0)

使用FruitAddict的评论:

let buttonImg = ResizeImage(UIImage(named: "Blokker")!, targetSize: CGSize(width: 50, height: 50)).imageWithRenderingMode(.AlwaysOriginal)

为遇到同样问题的人解决了图像问题!

到目前为止框架问题没有改变..

答案 1 :(得分:0)

问题的第一部分我已经在评论中回答了

如果您希望图像与来源

相同,请使用imageView.imageRenderingMode = .AlwaysOriginal

imageView.imageRenderingMode = .AlwaysTemplate如果您希望图像与其容器颜色相同(没有Alpha通道的图像将是彩色方块)

对于帧问题,为什么你是以下行?删除它。

view.addSubview(buttonTest) 

Buttontest已经有了一个superview,因为它是storyboard / xib的一个出口。另外,如果您使用storyboard / xib设计按钮,请不要更改frame rect。您应该学习如何使用约束。

答案 2 :(得分:0)

据我说,请使用SDWebImage ThirdParty库,请点击以下链接: -

https://github.com/rs/SDWebImage

或者您也可以通过pod安装并使用此库....

我使用swift语言向您展示代码: -

 let imageurl: NSURL? =  NSURL(string: "")

  imageview1.sd_setImageWithURL(url, placeholderImage:UIImage(named:"Ahmedabad_BRTS.jpg"))
相关问题