UIImageView not resizing - ios

I'm using Swift 3.0 with Xcode 8 and I'm having some problems with image resizing. Here is the code where i set my UIImage frame.
open func setData(_ data: Any?, image: String) {
self.textLabel?.font = UIFont.boldSystemFont(ofSize: 10)
self.textLabel?.textColor = UIColor(hex: "000000")
if let menuText = data as? String {
self.textLabel?.text = menuText
}
self.imageView?.contentMode = UIViewContentMode.scaleToFill
self.imageView?.frame = CGRect(x: 12, y: 8, width: 10, height: 10)
self.imageView?.image = UIImage(named: image)
self.imageView?.clipsToBounds = true
}
And here is where I call my function inside my tableView. I don't have any problem with setting the image, but ONLY with resize. When i use smaller images, the image is smaller, when i use bigger images, the image gets bigger, it doesnt resize.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = BaseTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: BaseTableViewCell.identifier)
cell.setData(menus[indexPath.row], image: images[indexPath.row])
return cell
}

I have solved it by using this resize function to resize my image and then place in the ImageView
func imageResize(image:UIImage,imageSize:CGSize)->UIImage
{
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0)
[image .draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))]
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return newImage!
}

If you are using default image view of uitableview cell than you won't be able to resize it. Some default constraints are already there.
You have two options :
create a subclass of uitableview cell and use your own image view (don't create the outlet with name imageView, try something else).
Resize the image using https://stackoverflow.com/a/45100626/5383852

Related

How to change an image I set in tableView(_:willDisplayHeaderView:forSection:)?

I set an image for each tableView's header section in tableView(_:willDisplayHeaderView:forSection:) in this way:
let image = UIImage(named: "arrow-down")
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 220, y: 12, width: 10, height: 5)
view.addSubview(imageView)
header.addSubview(imageView)
To try to change the image (it's a chevron I use to show the possibility to collapse the section) I tried in this way but it sets the top header only, instead I would like to replace the image in the specific section (I have got the section item Int):
let frame = CGRect(x: 220, y: 12, width: 10, height: 5)
let headerImageView = UIImageView(frame: frame)
let image: UIImage = UIImage(named: "arrow-up")!
headerImageView.image = image // sets the top header only
How can I change the image displayed at a specific section?
I read this question How to change button image added to TableView section header but I have not a button in the section.
I also found other similar questions but I don't know well Objective-C and can't convert the code easily in current Swift without to get errors.
If you know the specific position, you can do it at the moment when the table is loading the elements if what you want is to add an initial image (Option 1), if what you want is that when you touch the cell change the image you can do it the following way (Option 2)
-----------
Option 1
-----------
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row == //index of your cell){
let frame = CGRect(x: 220, y: 12, width: 10, height: 5)
let headerImageView = UIImageView(frame: frame)
let image: UIImage = UIImage(named: "arrow-up")!
headerImageView.image = image
}
}
-----------
Option 2
-----------
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(indexPath.row == //index of your cell){
let frame = CGRect(x: 220, y: 12, width: 10, height: 5)
let headerImageView = UIImageView(frame: frame)
let image: UIImage = UIImage(named: "arrow-up")!
headerImageView.image = image
}
}

Resizing icon using imageView

I've got the following code (updated):
// Set cell row height
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension // Auto-size cell based on content
}
// Set cell content
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
let weatherObject = forecastData[indexPath.section]
// Convert UNIX time into readable format
let sunriseUNIX = weatherObject.sunriseTime
let sunriseDate = Date(timeIntervalSince1970: Double(sunriseUNIX))
let sunsetUNIX = weatherObject.sunsetTime
let sunsetDate = Date(timeIntervalSince1970: Double(sunsetUNIX))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let sunriseConv = dateFormatter.string(from: sunriseDate)
let sunsetConv = dateFormatter.string(from: sunsetDate)
cell.textLabel?.text = weatherObject.summary
cell.detailTextLabel?.text = "Max: \(Int(round(weatherObject.temperatureMax))) °F / Min: \(Int(round(weatherObject.temperatureMin))) °F \nWill feel like \(Int(round(weatherObject.apparentTemperatureMax))) °F \nSunrise: \(sunriseConv) Sunset: \(sunsetConv) \nRelative Humidity: \(Int((weatherObject.humidity)*100))% \nMoon Phase: \(round(weatherObject.moonPhase))"
cell.detailTextLabel!.numberOfLines = 0
cell.imageView?.image = UIImage(named: weatherObject.icon)
cell.imageView?.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
cell.imageView?.contentMode = .scaleAspectFit
cell.imageView?.clipsToBounds = true // clipping will help check actual frame of image
cell.layoutIfNeeded()
cell.setNeedsDisplay() // try to reset display, if not updating your image scale automatically
return cell
}
...(Still) yielding the following result:
I'm trying to get the 'icon' images sized 10 x 10 pixels, yet the above code doesn't work. Regardless of the values in CGRect, the 'icons' remain the same size.
Any pointers, alternatives would be appreciated!!
Thanks in advance.
You can use code as shown under:
var newImgThumb : UIImageView
newImgThumb = UIImageView(frame:CGRectMake(0, 0, 100, 70))
newImgThumb.contentMode = .ScaleAspectFit
Hope u got it!!!
You should set up the content mode of the images properly in order to scale them to the correct size.
cell.imageView.contentMode = .scaleAspectFit
Set content mode of cell image view as scaleAspectFit
cell.imageView?.image = UIImage(named: weatherObject.icon)
cell.imageView?.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
cell.imageView?.contentMode = .scaleAspectFit
cell.imageView?.clipsToBounds = true // clipping will help check actual frame of image
cell.layoutIfNeeded()
//cell.setNeedsDisplay() // try to reset display, if not updating your image scale automatically
A good advice for you, Use Custom tableview cell and set all elements according to your choice/requirement.
Here is reference tutorial for Custom Tableview cell. Let me know, if you face any problem with Custom Tableview Cell.
Custom tableview cell, gives flexibility to arrange all cell elements according to your need.

Swift 3 - How to take a screenshot of specific UITableView row

I need to have a screenshot of a specific UITableView row and remove/add content to the cell before the screenshot.
For example: the cell contains only a text and a share button. On share button click, I want the app to generate an image with the text and my app logo on the top (without the share button).
What is the best approach to do this? and how?
Thanks in advance.
#Nirav already gave you a hint in the comment section with this post:
How to take screenshot of portion of UIView?
So, you have now to get the Rect of the cell in the superview, so i made a sample action method:
#IBOutlet var snapImageView: UIImageView!
#IBAction func snapshotrow(_ sender: Any) {
//get the cell
if let cell = myTable.cellForRow(at: IndexPath(row: 0, section: 0)) as? MyCustomCellClass {
//hide button
cell.shareButton.isHidden = true
let rectOfCellInTableView = myTable.rectForRow(at: IndexPath(row: 0, section: 0))
let rectOfCellInSuperview = myTable.convert(rectOfCellInTableView, to: myTable.superview)
snapImageView.image = self.view.snapshot(of: rectOfCellInSuperview)
let finalImage = saveImage(rowImage: snapImageView.image)
//test final image
snapViewImage.image = finalImage
}
}
func saveImage(rowImage: UIImage) -> UIImage {
let bottomImage = rowImage
let topImage = UIImage(named: "myLogo")!
let newSize = CGSize.init(width: 41, height: 41) // set this to what you need
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
bottomImage.draw(in: CGRect(origin: .zero, size: newSize))
topImage.draw(in: CGRect(origin: .zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
and I was able to get the snapshot of the 0th cell of my table view and assigned it to the snapImageView.
Now the last step is to save the image to the camera roll, there are lots of related post out there in SO.
Source: Get Cell position in UITableview
Adding logo and hiding share button: Saving an image on top of another image in Swift

How to resize a cell.imageView in a TableView and apply tintColor in Swift

I have a tableView with a cell created in cellForRowAtIndexPath and add some dummy text:
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: "cell")
cell.textLabel?.text = "Test Title"
cell.detailTextLabel?.text = "Test detail label"
Then I add a test image to the cell's imageView:
var image = UIImage(named: "cd.png")
cell.imageView!.image = image
Result:
To adjust the color, I use the following code:
cell.imageView?.tintColor = UIColor.redColor()
Result:
The image is too big in the cell, so I adjust the size using the following code:
var itemSize:CGSize = CGSizeMake(20, 20)
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.mainScreen().scale)
var imageRect : CGRect = CGRectMake(0, 0, itemSize.width, itemSize.height)
cell.imageView!.image?.drawInRect(imageRect)
cell.imageView!.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Whilst the image does resize, the tintColor is lost:
Any ideas please?
Solution Without custom cell
func imageWithImage(image: UIImage, scaledToSize newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0 ,y: 0 ,width: newSize.width ,height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.withRenderingMode(.alwaysOriginal)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.imageView?.tintColor = UIColor.green
cell.imageView?.image = imageWithImage(UIImage(named: "imageName")!, scaledToSize: CGSize(width: 20, height: 20))
// Configure the cell...
return cell
}
You can do it by another way :
1) Create custom cell with your own UIImageView size and 2 separate labels
2) Add UIImageView as Subview of Cell
var cellImg : UIImageView = UIImageView(frame: CGRectMake(5, 5, 50, 50))
cellImg.image = UIImage(named: "yourimage.png")
cell.addSubview(cellImg)
in swift 4 :
func image( _ image:UIImage, withSize newSize:CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.withRenderingMode(.automatic)
}
cell.imageView?.image = image(UIImage(named: "yourImage.png")!, withSize: CGSize(width: 30, height: 30))
For Swift 3
func imageWithImage(image:UIImage,scaledToSize newSize:CGSize)->UIImage{
UIGraphicsBeginImageContext( newSize )
image.draw(in: CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.withRenderingMode(.alwaysTemplate)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.imageView?.tintColor = UIColor.greenColor()
cell.imageView?.image = imageWithImage(image: UIImage(named: "imageName")!,scaledToSize: CGSize(width: 20, height: 20))
// Configure the cell...
return cell
}
For OBJECTIVE C without Custom tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"abc" forIndexPath:indexPath];
// Configure the cell...
if (cell==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"abc"];
}
cell.textLabel.text = [menuItemsArray objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:[menuItemsImagesArray objectAtIndex:indexPath.row]];
CGSize itemSize = CGSizeMake(20, 20);
UIGraphicsBeginImageContextWithOptions(itemSize, false, self.view.contentScaleFactor);
CGRect imageRect = CGRectMake(0, 0, itemSize.width, itemSize.height);
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cell; }
I came here because I was trying to find the answer to same question.
There are several answers that manipulate the image. I was having the same issue. but didn't want to manipulate the image.
What I did find that my images were 200x200 and dropped them as 1x.
I moved them to the 3x section and iOS would automatically resize them more to icon size. For everyone's reference I have added 1x vs 3x comparison
I thought to post as it did solve my issue. It might be helpful to anyone with the same intention as mine.
happy coding.
SwiftUI solution
Image("YourImage")
.resizable()
.scaledToFit()
.frame(width: 40, height: 40)
In case anyone is working with Xamarin, here is the snippet
private static UIImage ImageWithImage(UIImage image, CGSize newSize)
{
UIGraphics.BeginImageContext(newSize);
image.Draw(new CGRect(x: 0, y: 0, width: newSize.Width, height: newSize.Height));
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
}

How to resize an UIImageView (swift)

I'm a beginner with swift and I can't get the resize of a UIImageView working.
Here is my current layout :
What I want is to resize the images to occupy half the screen's width (2 images per row).
Here is my storyboard :
Here is the function drawing the collection view inside my controller :
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
var cell : MenuInspirationCellView = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as MenuInspirationCellView
cell.imageView.layer.borderWidth = 2
cell.imageView.layer.borderColor = UIColor.yellowColor().CGColor
//This is my first approach trying to modify the frame :
cell.imageView.frame = CGRectMake(0,0, self.view.bounds.width / 2,v120)
var cellImage : UIImage = UIImage(data: NSData(contentsOfURL: NSURL(string: images[indexPath.row])))
cell.imageView.image = cellImage;
//This is my second approach (based on http://www.snip2code.com/Snippet/89236/Resize-Image-in-iOS-Swift) :
// to resize an image to dimension 52x52
//var newSize:CGSize = CGSize(width: 52,height: 52)
//let rect = CGRectMake(0,0, newSize.width, newSize.height)
//UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
// image is a variable of type UIImage
//cellImage.drawInRect(rect)
//let newImage = UIGraphicsGetImageFromCurrentImageContext()
//UIGraphicsEndImageContext()
// resized image is stored in constant newImage
//cell.imageView.image = newImage;
//This is my thrid approach (based on https://gist.github.com/hcatlin/180e81cd961573e3c54d, of course i added his functions but I don't show them here for the sake of readability) :
//cell.imageView.image = self.RBSquareImageTo(cellImage, size: CGSize(width: 80, height: 80))
return cell
}
Any leads to sort this out ?
SWIFT:
func imageResize(imageObj:UIImage, sizeChange:CGSize)-> UIImage {
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
imageObj.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext() // !!!
return scaledImage
}
The sizes of your cells are decided by your UICollectionViewLayout object, which is a UICollectionViewFlowLayout in your case. If you want all of your cells to be the same size, you can configure the properties on the layout itself; itemSize and minimumInterimSpacing will do the trick. Alternatively, if you want your cells to be different sizes, say depending on the image each contains or whatever, you needs your collection view delegate to implement the UICollectionViewDelegateFlowLayout method:
optional func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize
returning the size you want for each cell.
Following this tutorials you can resize UIImage, In that tutorial described fully .. Image Resize in swift ios8
func imageResize (imageObj:UIImage, sizeChange:CGSize)-> UIImage{
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
imageObj.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
return scaledImage
}
Here you can also see many tutorials about Swift language Visit Here iPhone & iPad Application Development Help World

Resources