UIImage not in wanted location of UIImageView - ios

Problem solved, s. comment on first answer...
I am using a plugin called Carlos to load images from the cache if they have already been fetched once. However, the images I load only appear in the first of my (3) pages (I have a scrollView with pagingEnabled set to true and each of these pages shall contain the userProfilePicture). In addition to that, the image(s) appearing on the first page also has(-ve) no offsets. Combining those two informations one can assume that all (3 due to 3 pages) images are currently located on the first page with an offset of 0 and 0 for x and y respectively (see image below)(therefore I added '(s)' and '(-ve)' previously). How can I place the loaded image in the UIImageView? Does anyone have an idea how to solve this problem?
Code (Swift)
let userProfilePicture: UIImageView = {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let profileImageFrame = CGRect(x: statusBarHeight / 2, y: statusBarHeight, width: 50, height: 50)
let profileImageView = UIImageView(frame: profileImageFrame)
//set backgroundcolor (placeholder as sort of a place holder)
profileImageView.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
let imageUrl = NSURL(string: "https://like.to.myImageWith50pixels.jpg")!
let cache = MemoryCacheLevel().compose(DiskCacheLevel()).compose(NetworkFetcher())
cache.get((imageUrl as NetworkFetcher.KeyType) as NetworkFetcher.KeyType)
.onSuccess { value in
let profileImage = UIImage(data: value as Data)
profileImageView.image = profileImage
}
.onFailure { error in
print("An error occurred :( \(error)")
}
profileImageView.translatesAutoresizingMaskIntoConstraints = false
//round picture
profileImageView.layer.borderWidth = 1
profileImageView.layer.masksToBounds = false
profileImageView.layer.borderColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 0.75).cgColor
profileImageView.layer.cornerRadius = profileImageView.frame.height/2
profileImageView.clipsToBounds = true
return profileImageView
}()

one more solution I made it. Make a singleton class with a NSCache parameter. using GCD fetch images and save image data for location key.
for every time you want image. use singleton class NSCache parameter to fetch and image from web or local cache which every is available first.

Related

Progressview tintColorIssue

I have created a progressview according to number images as you can see in below code.
let view = UIView()
view.backgroundColor = .clear
let progressView = UIProgressView(frame: CGRect(x: 0, y: 0, width: frameOfParentView.width/3 - 8, height: 30))
progressView.progressViewStyle = .default
progressView.progress = 0.0
progressView.tintColor = .red
progressView.trackTintColor = .gray
progressView.layoutIfNeeded()
view.addSubview(progressView)
self.arrayOfProgrssView.append(progressView)
As you can see in gif at starting point tintColor alpha is little bit less but when it tense to reach at 100% it is fully red.
I also tried with below code:-
progressView.progressTintColor = .red
but did not get expected result.
To perform animation,
DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) {
UIView.animate(withDuration: self.animationInMS) {
progressView.setProgress(1, animated: true)
}
}
progressView.layoutIfNeeded()
Issue in iOS 15:-
As you see below result with other colour.
Note:- I have checked in iOS 12.4 it's working properly as you can see into image.
Please let me know is anything require from my side.
Thanks in advance
This does appear to be "new behavior" where the alpha value matches the percent completion -- although, after some quick searching I haven't found any documentation on it.
One option as a work-around: set the .progressImage instead of the tint color.
So, use your favorite code to generate a solid-color image, such as:
extension UIImage {
public static func withColor(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let image = UIGraphicsImageRenderer(size: size, format: format).image { rendererContext in
color.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
return image
}
}
Then, instead of:
progressView.tintColor = .red
use:
let img = UIImage.withColor(.red)
progressView.progressImage = img
Not fully tested, but to avoid the need to change existing code, you might also try:
extension UIProgressView {
open override var tintColor: UIColor! {
didSet {
let img = UIImage.withColor(tintColor)
progressImage = img
}
}
}
Now you can keep your existing progressView.tintColor = .red

Update UI with Firebase Observe Data (Swift)

I am having a hard time updating the UI on my Swift app while observing a Firebase node. I have a red_value, a green_value, and a blue_value stored in firebase which is being fetched and used to construct a UIColor which is then used to update the background color of a button on my UI. I am successfully fetching the color values, but when i try to update the UI from within the observe closure, the color always turns out to be white and I can't figure out why.
My code can be found below for a better idea of what i am trying to accomplish when loading the view:
override func viewDidLoad() {
super.viewDidLoad()
self.charitiesReference.child(charityUsername!).observe(.value) {
snapshot in
let values = snapshot.value as! [String: Any]
let redValue = values["red_value"] as! CGFloat
let greenValue = values["green_value"] as! CGFloat
let blueValue = values["blue_value"] as! CGFloat
let charityColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
let ripplerFollowers = values["follower_ripplers"] as! [String: Bool]
if ripplerFollowers["\(self.username!)"] ?? false {
self.followOrFollowingButton.setTitle("Following", for: .normal)
//ERROR -> The line below is producing a white background on my button
self.followOrFollowingButton.backgroundColor = charityColor
} else {
self.followOrFollowingButton.setTitle("Follow", for: .normal)
self.followOrFollowingButton.backgroundColor = .clear
}
}
}
Update:
When I change self.followOrFollowingButton.backgroundColor = charityColor line to self.followOrFollowingButton.backgroundColor = UIColor(red: 0, green: 120, blue: 120, alpha: 1.0)
it works as intended, which means that something is going on with the redValue, greenValue, & blueValue variables
Thank you in advance for your help!
As it turned out, I had forgotten to divide each of the color values by 255 to put them in the 0.0 - 1.0 range. if the value is above 1.0, it is set to 1.0, which resulted in the white color.
After dividing by 255, it's working like a charm

Create a masked UIView

I am attempting to do something that I thought would be possible, but have no idea how to start.
I have created a UIView and would like it to be filled with colour, but in the shape defined by an image mask. i.e. I have a PNG with alpha, and I would like the UIView I have created to be UIColor.blue in the shape of that PNG.
To show just how stupid I am, here is the absolute rubbish I have attempted so far - trying to generate just a simple square doesn't even work for me, hence it's all commented out.
let rocketColourList: [UIColor] = [UIColor.blue, UIColor.red, UIColor.green, UIColor.purple, UIColor.orange]
var rocketColourNum: Int = 0
var rocketAngleNum: Int = 0
var rocketAngle: Double {
return Double(rocketAngleNum) * Double.pi / 4
}
var rocketColour = UIColor.black
public func drawRocket (){
rocketColour.set()
self.clipsToBounds = true
self.backgroundColor = UIColor.red
imageView.image = UIImage(named: ("rocketMask"))
addSubview(imageView)
//maskimage.frame = self.frame
//let someRect = CGRect (x: 1, y: 1, width: 1000, height: 1000)
//let someRect = CGRect (self.frame)
//let fillPath = UIBezierPath(rect:someRect)
//fillPath.fill()
//setNeedsDisplay()
}
}
Set image as template, then set tint color for UIImageView. Something like that:
guard let let image = UIImage(named: "rocketMask")?.withRenderingMode(.alwaysTemplate) else { return }
imageView.image = image
imageView.tintColor = .blue
Also you can do that through the images assets:

Image not showing in imageView if I used circular image

I have a table view and I need to show author_img in section header. In ViewForSectionHeader method, I want to make the image to be circular. But If I did that, the images are not showing at all, no matter in simulator or in real device. If I remove the code, uiimageview will show the images normally. I set up the width and height constraint for uiimageview because I want to get fixed size of showing images. So Any ideas, please?
cell.author_img.layer.cornerRadius = cell.author_img.frame.size.width/2
cell.author_img.layer.masksToBounds = true
// add a boundary for thumb
cell.author_img.layer.borderWidth = 1.5
cell.author_img.layer.borderColor = UIColor.whiteColor().CGColor
It may come from the fact that you are setting the cornerRadius too early, the final size of your author_img is not fixed yet.
Try to set that cornerRadius when you are sure that the layout of your cell has been entirely calculated.
For test purpose, just to make sure it is coming from this behaviour, try to hardcode the cornerRadius.
cell.author_img.layer.cornerRadius = 10
If your image has a slight cornerRadius, it means that the issue is coming from what I explained earlier, if it is still not showing, it is coming from something else.
If it does come from the fact the size of your image is not fixed, try to set your cornerRadius in something like viewDidAppear, I mean the latest you can do.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView : UIView = UIView.init(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
headerView.backgroundColor = UIColor(red: 75/255.0, green: 193/255.0, blue: 210/255.0, alpha: 1.0)
let iconimage: UIImageView = UIImageView(frame: CGRectMake(10, 0, 40, 40))
iconimage.image = UIImage(named: "original.jpg")
iconimage.layer.cornerRadius = iconimage.frame.size.height / 2
iconimage.layer.borderColor = UIColor.whiteColor().CGColor
iconimage.layer.borderWidth = 1.0
iconimage.clipsToBounds = true
let subjectNameLabel = UILabel(frame: CGRect(x: 60, y: 4, width: 250, height: 35))
subjectNameLabel.textAlignment = NSTextAlignment.Center
subjectNameLabel.font = UIFont (name: "HelveticaNeue", size: 16)
subjectNameLabel.textColor = UIColor.whiteColor()
headerView.userInteractionEnabled = true
if isFristtime == true {
let subjectNameTxtValue = "Mile Ho Tum Humko"
subjectNameLabel.text = subjectNameTxtValue
}else{
let subjectNameTxtValue = "Saiyaan"
subjectNameLabel.text = subjectNameTxtValue
}
subjectNameLabel.backgroundColor = UIColor(red: 75/255.0, green: 193/255.0, blue: 210/255.0, alpha: 1.0)
headerView.addSubview(iconimage)
headerView.addSubview(subjectNameLabel)
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}

iOS adding image view at center programmatically [duplicate]

This question already has an answer here:
How do I add a UIview to an imageView while ensuring that the contents of the UIView are inside the it's frame?
(1 answer)
Closed 6 years ago.
I attempt to create a button panel with 3 buttons in two rows. Given it does not need to be flexible, I tried
class MyViewController : UIViewController {
#IBOutlet weak var buttonPanel: UIView! // auto layout, aligned to the bottom of screen
var icon0: UIImageView!
var icon1: UIImageView!
...
var icon5: UIImageView!
override func viewDidLoad() {
super.viewDidLoad();
icon0 = UIImageView(image: UIImage(named: "ic_smiley_gray.png"))
icon1 = UIImageView(image: UIImage(named: "ic_smiley_gray.png"))
// ...
icon5 = UIImageView(image: UIImage(named: "ic_smiley_gray.png"))
let icons = [icon0, icon1, ..., icon5]
let btnCellW = CGFloat(self.view.bounds.width) / 3.0
let btnCellH = buttonPanel.frame.height / 2.0
for j in 0..<2 {
for i in 0..<3 {
let rect = CGRect(x: btnCellW * CGFloat(i),
y: btnCellH * CGFloat(j),
width: btnCellW, height: btnCellH)
let cell = UIView(frame: rect)
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor.grayColor().CGColor
cell.layer.backgroundColor = UIColor(red: 0.85 + 0.15 * CGFloat(1 - i % 2), green: 0.85, blue: 0.85,
alpha: 1.0).CGColor
buttonPanel.addSubview(cell)
let ic = icons[i + j*3]
ic.center = cell.center
ic.layer.borderWidth = 0.5
ic.layer.borderColor = UIColor.brownColor().CGColor
NSLog("adding icon \(ic.image) at \(ic.center.x) x \(ic.center.y)")
cell.addSubview(ic)
}
}
The button panel is drawn correctly with the cells, but only the first cell has an image, so the image asset is good. Other cells are blank. What is my problem?
The problem is this line:
ic.center = cell.center
That can't possibly be right, because the center of a view is in the coordinates of its superview. You are mixing apples and oranges. You want the center of ic to be centered within its superview, but instead you are putting it at the same coordinates relative to cell that cell has relative to buttonPanel! Thus, all the ic images except the first are _outside the boundsof theircell`, and are thus invisible.
Instead, figure out the center of cell bounds and put the center of ic there: i.e., at CGPoint(x:cell.bounds.width/2, y:cell.bounds.height/2).

Resources