【问题标题】:How I get the image of a button in swift?如何快速获取按钮的图像?
【发布时间】:2018-02-19 08:54:34
【问题描述】:

我使用此代码将图像设置为按钮

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {


    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage


        btnImg1.contentMode = .scaleAspectFit
        btnImg1.setImage(chosenImage, for: UIControlState.normal)

dismiss(animated: true, completion: nil)
}

现在我如何才能获得选定的图像,或者我的意思是如何获得按钮的图像?我希望图像将其保存在某个地方.. 请帮忙,提前谢谢

【问题讨论】:

  • 您在寻找 btnImg1.imageView?.image
  • 在 didFinishPickingMediaWithInfo 方法中,当您将图像设置为按钮对象时,将其副本保存到另一个 uiimage 对象,并且当您要将图像保存到某个地方时,只需从 uiiimage 对象中获取图像。
  • 您也只需将图像存储在图像的全局对象中
  • 首先,您应该在UIButtontouchUpInside 事件上添加一个目标,然后您可以通过let image: UIImage = yourButton.image(for: .normal)! 检索图像

标签: ios swift image button uiimagepickercontroller


【解决方案1】:

UIButton 包含 ImageView,当你将图像分配给 UIImageView 时,你可以得到它的 .image 属性

所以对于 UIButton 获取 ImageView 然后获取 Image

button.imageView?.image 会将图像分配给 UIButton 如果您的按钮具有不同的状态图像,您也可以使用 .

    button.image(for: .normal or what ever state)
    button.imageView?.image   

(如果您使用 .normal 设置图像,两者都会给出相同的结果)

@Rooh Al-mahaba 如果你有 UIButton 对象,你可以访问 UIImageView 的所有属性,因为 UIButton 包含一个 UIImageView 来处理图像相关部分

【讨论】:

  • @RoohAl-mahaba 如果我的答案是您想要的,请将其标记为正确答案
【解决方案2】:

您可以简单地使用以下代码从 Button 获取图像:

    let image = UIImage(named: "testImage")
    let button = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0))
    button.setImage(image, for: UIControlState.normal)

    //Get Image Back from Button
    let imageFromButton : UIImage = button.image(for: UIControlState.normal)

【讨论】:

    【解决方案3】:

    您可以使用以下代码获取按钮的图像:

    let btnImag = btnImg1.image(for: .normal)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多