Frame of UIImageView changes after setting new image - ios

I have a UIImageView which is instantiated with an low resolution thumbnail from core-data. After the view has been presented the loading of the high-res web version starts which will replace the original image in the UIImageView. The problem however is that the frame changes once the download of the high-res version completes. This can't happen because of the blur layer on top of the original image which will then be a smaller size then the original image. I use the following code:
let imageData = member.picture
if let imageData = imageData {
let image = imageFromData(imageData)
// Setup pictures
self.profilePicture.image = image
self.profilePictureBlurred.image = image
self.profilePictureBlurred.clipsToBounds = true
// Make profilePicture round
let width = self.profilePicture.frame.width
self.profilePicture.layer.cornerRadius = width * 0.5
self.profilePicture.layer.masksToBounds = true
self.profilePicture.layer.borderColor = UIColor.whiteColor().CGColor
self.profilePicture.layer.borderWidth = 2.0
// Blur profilePictureBlurred
// Create Effects
let blur = UIBlurEffect(style: .Light)
let vibrancy = UIVibrancyEffect(forBlurEffect: blur)
let effectView = UIVisualEffectView(effect: blur)
effectView.frame = self.profilePictureBlurred.frame
let vibrantView = UIVisualEffectView(effect: vibrancy)
vibrantView.frame = self.profilePictureBlurred.frame
print(self.profilePictureBlurred.frame)
// Add effects to profilePictureBlurred
self.profilePictureBlurred.addSubview(effectView)
self.profilePictureBlurred.addSubview(vibrantView)
let iPid = Int(member.iPid!)
getImageForPerson(iPid, completionHandler: { (image,error) in
if error == nil {
self.profilePicture.image = image
self.profilePictureBlurred.image = image
print(self.profilePictureBlurred.frame)
} else {
print("Error: \(error)")
}
})
} else {
print("No Image Data")
}
The size of the frame changes after the download completes, printlog:
(0.0, 0.0, 600.0, 150.0)
(0.0, 0.0, 375.0, 167.0)
This means that the blur effect no longer covers the entire UIImageView thus resulting in an ugly effect. Why does the UIImageView change size and what should be the correct way to set an image in a UIImageView for a second time?
The goal is to create something like the LinkedIn contact view
Edit: The outlets:
#IBOutlet weak var profilePictureBlurred: UIImageView!
#IBOutlet weak var profilePicture: UIImageView!

Related

Swift 5: Better way/approach to add image border on photo editing app?

In case the title doesn't make sense, i'm trying to make a photo editing app where user can add border to their photo. For now, i'm testing a white border.
here is a gif sample of the app. (see how slow the slider is. It's meant to be smooth like any other slider.)
Gif sample
My approach was, to render the white background to the image's size, and then render the image n% smaller to shrink it hence the border.
But i have come to a problem where when i'm testing on my device (iphone 7 plus) the slider was so laggy and slow as if it's taking so much time to compute the function.
Here are the codes for the function. This function serves as blend the background with the foreground. Background being plain white colour.
blendImages is a function located on my adjustmentEngine class.
func blendImages(backgroundImg: UIImage,foregroundImg: UIImage) -> Data? {
// size variable
let contentSizeH = foregroundImg.size.height
let contentSizeW = foregroundImg.size.width
// the magic. how the image will scale in the view.
let topImageH = foregroundImg.size.height - (foregroundImg.size.height * imgSizeMultiplier)
let topImageW = foregroundImg.size.width - (foregroundImg.size.width * imgSizeMultiplier)
let bottomImage = backgroundImg
let topImage = foregroundImg
let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width : contentSizeW, height: contentSizeH))
let imgView2 = UIImageView(frame: CGRect(x: 0, y: 0, width: topImageW, height: topImageH))
// - Set Content mode to what you desire
imgView.contentMode = .scaleAspectFill
imgView2.contentMode = .scaleAspectFit
// - Set Images
imgView.image = bottomImage
imgView2.image = topImage
imgView2.center = imgView.center
// - Create UIView
let contentView = UIView(frame: CGRect(x: 0, y: 0, width: contentSizeW, height: contentSizeH))
contentView.addSubview(imgView)
contentView.addSubview(imgView2)
// - Set Size
let size = CGSize(width: contentSizeW, height: contentSizeH)
UIGraphicsBeginImageContextWithOptions(size, true, 0)
contentView.drawHierarchy(in: contentView.bounds, afterScreenUpdates: true)
guard let i = UIGraphicsGetImageFromCurrentImageContext(),
let data = i.jpegData(compressionQuality: 1.0)
else {return nil}
UIGraphicsEndImageContext()
return data
}
Below are the function i called to render it into uiImageView
guard let image = image else { return }
let borderColor = UIColor.white.image()
self.adjustmentEngine.borderColor = borderColor
self.adjustmentEngine.image = image
guard let combinedImageData: Data = self.adjustmentEngine.blendImages(backgroundImg: borderColor, foregroundImg: image) else {return}
let combinedImage = UIImage(data: combinedImageData)
self.imageView.image = combinedImage
This function will get the image and blend it with a new background colour for the border.
And finally, below are the codes for the slider's didChange function.
#IBAction func sliderDidChange(_ sender: UISlider) {
print(sender.value)
let borderColor = adjustmentEngine.borderColor
let image = adjustmentEngine.image
adjustmentEngine.imgSizeMultiplier = CGFloat(sender.value)
guard let combinedImageData: Data = self.adjustmentEngine.blendImages(backgroundImg: borderColor, foregroundImg: image) else {return}
let combinedImage = UIImage(data: combinedImageData)
self.imageView.image = combinedImage
}
So the question is, Is there a better way or optimised way to do this? Or a better approach?

Modifying images of generated imageViews on button click

I am creating a quiz app and having trouble changing the image which is displayed of a specific imageview that is generated in a for loop.
The following code is responsible for generating the imageviews based on the amount of questions in that specific quiz. It is called in the viewDidLoad() method:
var imageView = UIImageView()
func addProgressImages(to view: UIView, count: Int){
let screenSize = UIScreen.main.bounds.size
for i in 0..<count {
let spacing: CGFloat = 2
let tag = i + 888
let width: CGFloat = screenSize.width/CGFloat(count)
let height: CGFloat = width
if let view = view.viewWithTag(tag){
view.removeFromSuperview()
}
let x = spacing + CGFloat(i) * width
imageView = UIImageView(frame: CGRect(x: x, y: 100, width: width - spacing, height: height))
imageView.image = UIImage(named: "question_progress_empty")
imageView.tag = tag
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)
//print("imageviews displaying")
}
}
I have made an attempt to change some of the images to another image when the user selects an answer to that question with an if statement:
func changeImage() {
if (optA != questionAns){
imageView.image = UIImage(named: "wrong_answer")
print("opta")
}else if(optB == questionAns){
imageView.image = UIImage(named: "wrong_answer")
print("optb")
}else if(optC == questionAns){
print("optc")
imageView.image = UIImage(named: "wrong_answer")
}else{
print("if statement not initialised")
}
}
https://imgur.com/a/zwJ4EVn - This is the output of the above code
Currently, only the last image will be changed when a user clicks a button.
I need help with modifying the imageview which is related to that specific question, e.g. if question 2 is answered, only that imageview will change while the rest remain unmodified.
Hopefully that explanation made any sense, any input would be appreciated,
Thanks.
See you are doing few things wrong.
you have taken UIImageView as instance variable as below, so after
creating all the images its holding the reference to the last
imageView.
var imageView = UIImageView()
Make the var imageView as local variable and in the func
changeImage() get the proper imageView using its tag value then
try to change its image.
If any doubt plz comment.
How to get the imageView back in changeImage() check below code.
let tag = 888 + (questionNumber - 1)
if let imageView = view.viewWithTag(tag) as? UIImageView {
// Change imageView's image here
}
You will probably want to create an array of image views:
var imageViews = [UIImageView]()
And add your UIImagesViews to that array in your loop:
for i in 0..<count {
var imageView = UIImageView()
// additional setup...
imageViews.append(imageView)
}
Then, you can later iterate over your array and change the images:
for imageView in imageViews {
imageView.image = UIImage(named: "wrong_answer")
// etc.
}

Blurred Image as background in UIView

So I have an image that I am rendering in a view. For the background color of that uiview I actually want a UIImage. The way I was doing was taking the currentImageView and applying this function makeBlurEffect.
func makeBlurImage(targetImageView:UIImageView?)
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = targetImageView!.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
targetImageView?.addSubview(blurEffectView)
}
I typically set the background image and apply the blur filter inside the lazy var method that creates the UIView as shown below.
lazy var blurryBackGround : UIView = {
let blurryBackGround = UIView()
blurryBackGround.backgroundColor = UIColor.red
// blurryBackGround.backgroundColor = UIColor(i)
var blurryImage = currentImageView
blurryImage.makeBlurImage(blurryImage?)
return blurryBackGround
}()
I have also included the UIImageView creation:
//
lazy var currentEventImage : UIImageView = {
let currentEvent = UIImageView()
currentEvent.clipsToBounds = true
currentEvent.translatesAutoresizingMaskIntoConstraints = false
currentEvent.contentMode = .scaleAspectFill
currentEvent.isUserInteractionEnabled = true
currentEvent.layer.masksToBounds = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handlePromoVid))
currentEvent.isUserInteractionEnabled = true
currentEvent.addGestureRecognizer(tapGestureRecognizer)
return currentEvent
}()
Any idea how i would correctly do this?
The current way I implemented would blur the original image, change the blurred image to the main image and turning the background image to the unblurred image
Use following extension:
extension UIImageView {
func renderedImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
To capture currently presented imageView to an UIImage.
EDIT
How about you try not capturing it yet, just use this as a background:
lazy var blurryBackGround : UIView = {
let blurryBackGround = currentImageView
blurryBackGround.makeBlurImage(blurryBackGround)
return blurryBackGround
}()

How to tint an animated UIImageView?

I'm attempting to apply tint of a UIImageView consisting of programatically loaded animationImages. Currently using iOS 9.3.
I think I've tried every proposed solution found here for applying the tint including:
Setting the .renderMode on load with: let newImage: UIImage? =
UIImage(named: filename as
String)!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
Setting the tintView either in the Storyboard or programatically
with: zeroImageView.tintColor = UIColor.redColor()
Setting the image .renderMode through the UIImageView itself:
zeroImageView.image = zeroImageView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
Setting the UIImageView's renderMode through the Interface Builder
user defined runtime attributes: imageRenderingMode Number 2
The image sequence is of PNGs with transparency, so, I would like to re-colour the image and maintain the transparency.
I've had no luck and am sort of at a loss. Wondering if maybe these methods only work for a still UIAnimationView? Any help would be greatly appreciated, thanks!
Here's some code:
// Load all images
while let element = enumerator.nextObject() as? String {
if element.hasSuffix("png") {
let filename: NSString = "Digits/0/" + element
print(filename)
imageNames.append(filename as String)
let newImage: UIImage? = UIImage(named: filename as String)!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
images.append(newImage!)
zeroImageView.tintColor = UIColor.redColor()
}
}
// Make animated UIImageView
zeroImageView.userInteractionEnabled = false
zeroImageView.animationImages = images
zeroImageView.animationDuration = 2.0
zeroImageView.startAnimating()
zeroImageView.tintColor = UIColor.redColor()
Try this...
extension UIImage {
func image(withTint tint: UIColor) -> UIImage? {
guard let cgImage = cgImage else {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
let rect = CGRect(origin: .zero, size: size)
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(.normal)
context.clip(to: rect, mask: cgImage)
tint.setFill()
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
If none of those worked the next step I would do is programmatically place an empty UIView on top of the UIImageView. First off, it would not interfere with anything going on in the UIImageView.
I would check out this tutorial here: http://www.apptuitions.com/programmatically-creating-uiview-uislider-uiswitch-using-swift/
this will teach you how to programmatically add a UIView to the storyboard. I would add this code in the viewDidLoad() method.
The main thing you need to change is the background color of the UIView. First you have to decide what the color of the tint (which from what I see in your code is red) and then explicitly change the 'Alpha' of the color so that it is barely showing. You change the 'Alpha' because that is basically the opacity of the color.
Hope this helps.

Alternative way to show a UIPageControl (Swift)

I'm trying to add an arrow or like an image to correlate to how many view I have in my UIScrollView in swift. Something in line of this
(UPDATE) - My question is how do you insert an image into your scrollview that will tell it to go forward or backwards depending on how many images you have.
Now I know there is the UIPageControl but I'm looking into an alternative way to show that there is a picture and to the right or right and left. This is the code I have so far. I'll try the best I can to explain what I'm doing.
My picSource.count is data from a website that is carrying pictures
I'm multiplying my number of views by the screenwidth
This is an if else statement that shows if a picture is there post bgImage if not post no photoprovided image.
Let me know if you need more information or if I should revise. Thanks!
// Gallery
if (picSource.count > 1){
var picNum:CGFloat = CGFloat(picSource.count)
// UI News Image Scroller
var scroll = UIScrollView(frame:CGRectMake(-5, 650, screenWidth, 260))
scroll.pagingEnabled = true
scroll.showsHorizontalScrollIndicator = false
scroll.showsVerticalScrollIndicator = false
scroll.contentSize = CGSizeMake(picNum*screenWidth, 220)
// Number of views
var numberOfViews = picSource.count
var imageName = ""
// Loop to add views to scroll view
for (var i = 0; i < numberOfViews; i++){
var myIntValue:Int = Int(screenWidth)
var xOrigin = i * myIntValue
// Creates UIImageView instance using myImage
var scrollImageView = UIImageView(frame: CGRect(origin: CGPoint(x: xOrigin, y: 5), size: CGSize(width: screenWidth, height: 250)))
// Tests which image name needs to be used
imageName = picSource[i]
// Creates image object using specified image name "...jpg"
var url = NSURL(string: "http://www/images/cl/" + adID[adCurrentTag] + "/gallery/" + imageName)
var maybeError: NSError?
if var imageData :NSData = NSData(contentsOfURL: url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &maybeError) {
var bgImage = UIImage(data:imageData)
scrollImageView.contentMode = .ScaleAspectFit
scrollImageView.image = bgImage
// Adds Image to scroll view
scroll.addSubview(scrollImageView)
}else if let error = maybeError {
var photoNotProvided = UIImage(named:"noPhoto800x800.png")
var photoNotProvidedView = UIImageView(frame: CGRectMake(5, 650.0, screenWidth, 300.0))
scrollImageView.image = photoNotProvided
scroll.addSubview(scrollImageView)
}
}
border.addSubview(scroll)

Resources