简体   繁体   中英

how can I temporarily grey out my uiImage in swift?

in my app I'm letting user upload his image to my amazon s3 bucket. As soon as user captures the photo from the phone I show it on the screen and then the upload starts. At this point I start showing the progress bar that tells the user what's the stadium now. But is there a way of making the image greyed out for the time it's being uploaded and bring the original color when the upload is finished?

So far my code is as follows:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    let path = NSTemporaryDirectory().stringByAppendingString("image.jpeg")

    if let data = UIImageJPEGRepresentation(image, 0.8) {
        data.writeToFile(path, atomically: true)

    }

    self.dismissViewControllerAnimated(true, completion: {})

    let credentialsProvider = AWSCognitoCredentialsProvider(regionType:CognitoRegionType,
        identityPoolId:CognitoIdentityPoolId)
    let configuration = AWSServiceConfiguration(region:CognitoRegionType, credentialsProvider:credentialsProvider)
    AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

    let ext = "jpeg"

    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest.body = NSURL(string: "file://"+path)
    uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext
    uploadRequest.bucket = S3BucketName
    uploadRequest.contentType = "image/" + ext


//here I would like to present a greyed out photo until it's fully uploaded:
    imageView.image = image


    progressBar.hidden = false
    uploadRequest.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            if totalBytesExpectedToSend > 0 {
                self.progressBar.progress = Float(Double(totalBytesSent) / Double(totalBytesExpectedToSend))

            }
        })
    }
    let transferManager = AWSS3TransferManager.defaultS3TransferManager()
    transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
        if let error = task.error {
            print("Upload failed ❌ (\(error))")
        }
        if let exception = task.exception {
            print("Upload failed ❌ (\(exception))")
        }
        if task.result != nil {



            let s3URL = NSURL(string: "http://s3-eu-west-1.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
            //print("Uploaded to:\n\(s3URL)")
            self.photoURL = s3URL.absoluteString
            print(self.photoURL)

        }
        else {
            print("Unexpected empty result.")
        }
        return nil
    }


}

There are various ways you could do this. One simple way would be to put a UIView on top of your image view, set with opaque=false, and with a background color of dark gray with an alpha value of 50% or so. That would darken the image and make it look dull and low-contrast.

You could also put a 100% opaque black UIView under the image view, and then set the alpha on the image view to 50%.

You could put a CALayer on top of your image view's layer, with a background color of 50% opaque dark gray.

All of these approaches would give a similar effect.

Note that you could also put your image view in the content view of a UIVisualEffectView set for UIBlurEffect. That would blur your image rather than graying it out.

try

let image = UIImage(named: "image")?.withRenderingMode(.alwaysTemplate)
let imageView = UIImageView(image: image)
imageView.tintColor = UIColor.gray

The category below will allow to turn your image into black&white without changing initial image (not sure what exactly is implied by 'greyed' in your case, but it you could try it easily). (Swift 4)

extension UIImage {
    var grayed: UIImage {
        guard let ciImage = CIImage(image: self)
            else { return self }
        let filterParameters = [ kCIInputColorKey: CIColor.white, kCIInputIntensityKey: 1.0 ] as [String: Any]
        let grayscale = ciImage.applyingFilter("CIColorMonochrome", parameters: filterParameters)
        return UIImage(ciImage: grayscale)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM