i want to create an imageview with photo selected from photo library and display in the scrollview by pushing a button. But the image is not displayed after selection but only display when I push the button again. Can someone help me with this one please?
#IBAction func imageBtnPressed(_ sender: Any) {
imagePicker()
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
func imagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let selectedImage = info[.originalImage] as? UIImage
imageOnCanvas = selectedImage
dismiss(animated: true, completion: nil)
}
Your code does not pause just because the UIImagePickerController is presented. So, let's look at your code:
#IBAction func imageBtnPressed(_ sender: Any) {
imagePicker()
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
func imagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
So that is exactly like saying (substituting the contents of the imagePicker function for the function call):
#IBAction func imageBtnPressed(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
Well, as you can clearly see, you are referring to imageOnCanvas when it has not been set yet. The imagePicker is still showing; the user has not chosen a photo yet. But your code has completely come to an end. You've gone on to add a subview consisting of the image view containing the image that was in imageOnCanvas before the code started.
Related
Im having an issue where I implement sort of a profile screen, where you can go to a settings screen and edit your picture. When I click the profile settings button it takes me too a screen where I can edit the profile. The Following Code contains the action that pushes that view controller
import UIKit
class ProfileeViewController: UIViewController {
let profileSetupTransition = AlterProfileViewController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(profileFilledImage)
view.addSubview(profileeSettings)
navigationItem.title = "Profile"
///////////////////////////////////////////////////////////
//where all constraints f// constraints for the sign up label/title
_ = profileFilledImage.anchor(view.centerYAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 30, leftConstant: 25, bottomConstant: 0, rightConstant: 0, widthConstant: 15, heightConstant: 15)
//constraints for the sign up button
_ = profileeSettings.anchor(view.centerYAnchor, left: profileFilledImage.rightAnchor, bottom: nil, right: nil, topConstant: 30, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 140, heightConstant: 15)
///////////////////////////////////////////////////////////
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//will just be a nice looking image view to be next to the profile settings button
let profileFilledImage: UIImageView = {
let profileFilledImage = UIImageView()
profileFilledImage.image = UIImage(named: "icons8-User Filled-50")
profileFilledImage.clipsToBounds = true
profileFilledImage.translatesAutoresizingMaskIntoConstraints = false
profileFilledImage.contentMode = .scaleAspectFill
profileFilledImage.layer.masksToBounds = true
return profileFilledImage
}()
// will be the button that the user clicks to edit there profile settings
let profileeSettings: UIButton = {
let profileSetup = UIButton(type: .system)
profileSetup.setTitle("Profile Settings", for: .normal)
profileSetup.setTitleColor(.black, for: .normal)
profileSetup.addTarget(self, action: #selector(handleProfileSetuo), for: .touchUpInside)
return profileSetup
}()
func handleProfileSetuo(){
print("Profile Settings button tapped")
self.navigationController?.pushViewController(profileSetupTransition, animated: true)
//present(profileSetupTransition, animated: true, completion: nil)
}
}
Okay the following method handles selecting the image for the user's profile image. I use a UI Picker to select the image and than attempt to save it to a profile image view. When the picker dismisses it goes all the way back to the root view controller when it should go back to the page where I can continue to edit profile elements. The picture also does not change. Ive tried everything and nothing works. The code for that method is below
import UIKit
class AlterProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view?.backgroundColor = UIColor.white
navigationItem.title = "Profile Settings"
view.addSubview(selectProfileImage)
///Constraints for all views will go here
_ = selectProfileImage.anchor(view.centerYAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: -275, leftConstant: 135, bottomConstant: 0, rightConstant: 0, widthConstant: 100, heightConstant: 100)
// selectProfileImage.layer.cornerRadius = selectProfileImage.frame.size.width/2
///////////////////////////////////////////////
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
selectProfileImage.layer.cornerRadius = selectProfileImage.frame.size.width / 2;
selectProfileImage.layer.masksToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Where all buttons and labels will be added
//will just be a nice looking image view to be next to the profile settings button
lazy var selectProfileImage: UIImageView = {
let selectPicture = UIImageView()
// self.selectProfileImage.layer.cornerRadius = self.selectProfileImage.frame.size.width / 2;
selectPicture.image = UIImage(named: "Paris")
// selectPicture.layer.cornerRadius = selectPicture.frame.size.width / 2;
selectPicture.clipsToBounds = true
selectPicture.translatesAutoresizingMaskIntoConstraints = false
//selectPicture.layer.cornerRadius = selectPicture.frame.size.width/2
selectPicture.contentMode = .scaleAspectFill
selectPicture.isUserInteractionEnabled = true
selectPicture.layer.shouldRasterize = true
// will allow you to add a target to an image click
selectPicture.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
selectPicture.layer.masksToBounds = true
return selectPicture
}()
func handleSelectProfileImageView(tapGestureRecognizer: UITapGestureRecognizer) {
print("123")
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
// will dispaly info of image selected
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("info")
var selectedImageFromPicker: UIImage?
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage{
print((editedImage as AnyObject).size)
selectedImageFromPicker = editedImage
self.selectProfileImage.image = selectedImageFromPicker
picker.dismiss(animated: true, completion: nil)
}else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
print((originalImage as AnyObject).size)
selectedImageFromPicker = originalImage
self.selectProfileImage.image = selectedImageFromPicker
picker.dismiss(animated: true, completion: nil)
}
/*
if let selectedImage = selectedImageFromPicker {
selectProfileImage.image = selectedImage
}
*/
/* dismiss(animated: true, completion: {
self.selectProfileImage.image = selectedImageFromPicker
}) */
}
// will handle the picker being closed/canceled
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("picker canceled")
dismiss(animated: true, completion: nil)
}
///////////////////////////////////////////////////////////////////////////////////
}
Wherever you are assigning imagePicker to UIImagePickerController,
you need to write this
func handleSelectProfileImageView(tapGestureRecognizer: UITapGestureRecognizer) {
print("123")
let picker = UIImagePickerController()
picker.delegate = self
picker.modalPresentationStyle = .overCurrentcontext //This is what I added
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
I'm currently working on a application that allows a user to take a multiple images and it'll display it on a iCarousel. I'm not very strong at swift so I don't really know how to do it. My question is, "How do I append and display the image after the user takes a photo?" I'm only allowing a maximum of 3 photos. Here's my codes below:
var imageArray : NSMutableArray = NSMutableArray()
#IBOutlet weak var displayView: iCarousel!
override func viewDidLoad() {
super.viewDidLoad()
imageArray = ["1.jpg", "2.jpg", "3.jpg"]
displayView.type = iCarouselType.coverFlow2
displayView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
var imgView : UIImageView!
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
//let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
if view == nil {
imgView = UIImageView(frame: CGRect(x: 0, y:0, width: 250, height: 250))
imgView.contentMode = .scaleAspectFit
}
else
{
imgView = view as! UIImageView
}
imgView.image = UIImage(named:"\(imageArray.object(at: index))")
imgView.addGestureRecognizer(tapGesture)
tapGesture.numberOfTapsRequired = 1
imgView.isUserInteractionEnabled = true
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imgView.contentMode = .scaleToFill
imgView.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
return imgView
}
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if (option == .spacing)
{
return value * 1.8
}
return value
}
func numberOfItems(in carousel: iCarousel) -> Int {
return imageArray.count
}
func imageTapped(_ sender: UITapGestureRecognizer)
{
let alert = UIAlertController(title: "Pick Image Source", message: "", preferredStyle: .alert)
let takePhotoBtn = UIAlertAction(title: "Take Photo", style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
})
let galleryBtn = UIAlertAction(title: "Select from Gallery", style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary)
{
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
imagePicker.mediaTypes = ["public.image", "public.movie"] //Remove public.movie later
}
})
let cancelBtn = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) -> Void in
// print("Cancel")
})
alert.addAction(takePhotoBtn)
alert.addAction(galleryBtn)
alert.addAction(cancelBtn)
present(alert, animated: true, completion: { _ in })
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if imageArray.count == 3{
return //you can jump to Show the Carousel here
}
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imgView.contentMode = .scaleToFill
imgView.image = pickedImage
// Add image to Array Here
imageArray.add(image)
}
// you can also show refresh carousel from here so new image is availabe in carousel
picker.dismiss(animated: true, completion: nil)
}
if you are allowing maximum of 3 images then you can also write the checking condition in imageTapped function.
I have an image view in my view controller but weirdly I can't show my image inside of the imageview. It is located in the middle of the page or somewhere else in the other view controllers. My code of both image view and image picker are below.
And this is the output. Arrow image doesn' t show in expected area:
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.bottomAnchor.constraint(equalTo: nameTextField.topAnchor, constant: -12).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.image = UIImage(named: "arrow_long_left")
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
profileImageView.isUserInteractionEnabled = true
view.addSubview(profileImageView)
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
selectedImageFromPicker = editedImage
} else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
profileImageView.image = selectedImage
}
dismiss(animated: true, completion: nil)
}
func handleSelectProfileImageView() {
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
//picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
/*else if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.camera;
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}*/
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("canceled picker")
dismiss(animated: true, completion: nil)
}
Your code is off here:
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.bottomAnchor.constraint(equalTo: nameTextField.topAnchor, constant: -12).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 150).isActive = true
My guess is you want something more like this:
profileImageView.leadingAnchor.constraint(equalTo: nameTextField.trailingAnchor, constant:10).isActive = true
profileImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant:10).isActive = true
profileImageView.topAnchor.constraint(equalTo: nameTextField.topAnchor).isActive = true
profileImageView.bottomAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
If you want to fix the width and height to 150, you'll need to adjust a bit. But, right now you're anchored to the centerX of the view, so its horizontally centered. And anchored by the bottom to the top of the nameTextField - so of course its above the nameTextField
My app has a camera section. It takes a photo and then puts a watermark on the photo. However when the photo is saved, the whole screen is saved, not just the UIImageView. I just want the UIImageView to be saved. It's not that but because the menu bar at the button is not that big. I just think it would look better without the menu bar in the picture.
Photo of app just before taking photo:
Photo of how the picture taken is saved:
This is my code below.
import UIKit
class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var cameraScreen: UIImageView!
var screenView: UIImageView!
#IBAction func Camera(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)}}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!){
cameraScreen.image = image
self.dismiss(animated: true, completion: nil);
screenView = UIImageView()
screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let text = "Java"
let label = UILabel(frame: CGRect(x: 125, y: 400, width: self.view.frame.width, height: 300))
label.font = UIFont(name: label.font.fontName, size: 200)
label.textColor = UIColor.blue
label.alpha = 0.3
label.text = text
self.view.addSubview(screenView)
self.view.addSubview(label)
// i tried self, nil, nil
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)
let photo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(photo!, nil, nil, nil)
}
#IBAction func Save(_ sender: AnyObject) {
let alert = UIAlertController(title: "Image Saved", message: "", preferredStyle: .alert)
let okay = UIAlertAction(title: "OK.", style: .default, handler: nil)
alert.addAction(okay)
present(alert, animated: true, completion: nil)
}
}
These 5 lines of code are saving the photo but they are saving the whole screen. Basically the save button is acting as a screen on a laptop. I have a uiimageView outlet that is where the imagepicker displays the photo. I just want uimmmageview to be saved and not the whole page.
My outlets name is cameraScreen. I have tried to insert in the code but it does not work. My app takes a photo and then puts a graphic on it as well.
Here is the code
import UIKit
class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var cameraScreen: UIImageView!
var screenView: UIImageView!
#IBAction func Camera(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)}}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!){
cameraScreen.image = image
self.dismiss(animated: true, completion: nil);
screenView = UIImageView()
screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let text = "Java"
let label = UILabel(frame: CGRect(x: 125, y: 400, width: self.view.frame.width, height: 300))
label.font = UIFont(name: label.font.fontName, size: 200)
label.textColor = UIColor.blue
label.alpha = 0.3
label.text = text
self.view.addSubview(screenView)
self.view.addSubview(label)
}
#IBAction func Save(_ sender: AnyObject) {
let alert = UIAlertController(title: "Image Saved", message: "", preferredStyle: .alert)
let okay = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okay)
present(alert, animated: true, completion: nil)
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let photo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(photo!, nil, nil, nil)
}}