简体   繁体   中英

Change opacity on NSTextAttachment's image

I seem to have an issue with changing the transparency with an NSTextAttachment 's image in an NSAttributedString .

I have a string that I would like to fade in and out, but it seems that the images attached to the string do not fade out along with the text.

I have tried setting both the NSBackgroundColorAttributeName and NSForegroundColorAttributeName attribute to the desired alpha, but this does not work.

I am also not seeing an alpha or opacity property with NSTextAttachment , so the only option I am seeing is attaching a new UIImage with the corrected alpha, but this approach is going to be a last resort.

I am hoping somebody out there has a method for changing the alpha without me having to do that.

Either Objective-C or Swift code works for me.

As of right now, here is what I am doing:

import Foundation
import UIKit
import CoreGraphics
extension UIImage
{
    /// copyWithAlpha: Creates a copy of a UIImage with the new alpha
    /// - Parameter alpha: Alpha value to set new image to. Between (0.0 - 1.0)
    /// - Returns: UIImage
    ///```swift
    ///   let copyImage = originalImage.copyWithAlpha(1.0)
    func copyWithAlpha(alpha:CGFloat) -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
        drawAtPoint(CGPointZero,blendMode:.Normal, alpha:alpha);
        let alphaImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return alphaImage;
    }
}

This method is free for anybody to use. However, I am not happy about this method, because it requires me to keep a copy of the original UIImage , and apply the alpha every time to the original, I can't keep reapplying this to the UIImage that gets returned.

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