Hi I am new to swift 3 and Xcode 8 I have an issue in my below code Build get succeeded and it runs well in a simulator but image and text are not get showed what I did wrong?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
generateImageWithText(text: "HelloWorld")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#discardableResult
func generateImageWithText(text: String) -> UIImage
{
let image = UIImage(named: "apple_led.png")!
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.black
imageView.frame = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
let label = UILabel(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 50, height: 50)))
label.backgroundColor = UIColor.white
label.textAlignment = .center
label.textColor = UIColor.blue
label.text = text
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0);
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
print(image)
print(text)
print(label)
return imageWithText!
}
}
Try this
func mergeImageAndText(text: NSString, atPoint: CGPoint) -> UIImage{
let demoImage = UIImage(named: "test.png")!
// Setup the font specific variables
let textColor = UIColor.white
let textFont = UIFont(name: "Helvetica", size: 14)!
// Setup the image context using the passed image
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(demoImage.size, false, scale)
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
demoImage.draw(in: CGRect(x: 0, y: 0, width: 50, height:50))
let rect = CGRect(x: atPoint.x, y: atPoint.y, width: demoImage.size.width, height: demoImage.size.height)
// Draw the text into an image
text.draw(in: rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage!
}
Method Call:
let imagenew = self.mergeImageAndText(text: "TEST", atPoint: CGPoint(x: 10, y: 10))
Related
I have used Interface Builder to get UILabelViews to word wrap, but this is my first attempt to do it programmatically. I believe the issue is that although I'm setting:
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
I'm setting a line height which might conflict with these properties?
override func layoutSubviews() {
super.layoutSubviews()
imageViewContent.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
imageViewContent.loadImageWithURL(imageName!)
label.frame = CGRect(x: 0, y: 0, width: frame.size.width-10, height: 21)
label.center = imageViewContent.center
label.textAlignment = .center
label.clipsToBounds = true
label.layer.cornerRadius = 10.0
label.textColor = .white
label.font = UIFont(name: "AvenirNext-DemiBold", size: 15)
label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.text = photoName
}
As I suspected, hardcoding the height of the label prevented it from word wrapping. I've created a labelHeight variable and added a function at the bottom of the class to calculate the labelHeight based on the content, font size, and labelWidth I set. Code works fine now:
class NTWaterfallViewCell :UICollectionViewCell, NTTansitionWaterfallGridViewProtocol{
var photoName = ""
var imageName : String?
var labelHeight: CGFloat = 0.0
var imageViewContent : UIImageView = UIImageView()
var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.lightGray
contentView.addSubview(imageViewContent)
contentView.addSubview(label)
}
override func layoutSubviews() {
super.layoutSubviews()
imageViewContent.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
imageViewContent.loadImageWithURL(imageName!)
label.text = photoName
labelHeight = heightForText(photoName, width: frame.size.width-10)
label.frame = CGRect(x: 0, y: 0, width: frame.size.width-10, height: labelHeight)
label.center = imageViewContent.center
label.textAlignment = .center
label.clipsToBounds = true
label.layer.cornerRadius = 10.0
label.textColor = .white
label.font = UIFont(name: "AvenirNext-DemiBold", size: 15)
label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
}
func heightForText(_ text: String, width: CGFloat) -> CGFloat {
let font = UIFont(name: "AvenirNext-DemiBold", size: 15)
let rect = NSString(string: text).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(rect.height)
}
}
I am making an image slider that slides automatically every 2 seconds. The code I have wrote moves immediately to the next image without the slide animation, I want to fix it somehow by showing the scrollview scrolling, this is my code:
var imagesArray = [UIImage]()
static var i = 0
override func viewDidLoad() {
super.viewDidLoad()
imagesArray = [image1, image2, image3, image4]
for i in 0..<imagesArray.count{
let imageview = UIImageView()
imageview.image = imagesArray[i]
imageview.contentMode = .scaleAspectFit
let xPosition = self.view.frame.width * CGFloat(i)
imageview.frame = CGRect(x: xPosition, y: 0, width: self.imagesScrollView.frame.width, height: self.imagesScrollView.frame.height)
imagesScrollView.contentSize.width = imagesScrollView.frame.width * CGFloat(i+1)
imagesScrollView.addSubview(imageview)
}
}
override func viewDidAppear(_ animated: Bool) {
let scrollingTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(MenuViewController.newStartScrolling), userInfo: nil, repeats: true)
scrollingTimer.fire()
func newStartScrolling()
{
if MenuViewController.i == imagesArray.count {
MenuViewController.i = 0
}
let x = CGFloat(MenuViewController.i) * imagesScrollView.frame.size.width
imagesScrollView.contentOffset = CGPoint(x: x, y: 0)
MenuViewController.i += 1
}
Thank you.
Please try this code.
override func viewDidAppear(_ animated: Bool) {
imagesArray = [UIImage(named: "apple.jpg")!, UIImage(named: "empire.jpg")!, UIImage(named: "ottawa.jpg")!]
imagesScrollView.contentSize = CGSize(width: imagesScrollView.frame.width * CGFloat(imagesArray.count), height: imagesScrollView.frame.height)
for i in 0..<imagesArray.count{
let imageview = UIImageView()
imageview.image = imagesArray[i]
imageview.contentMode = .scaleAspectFill
imageview.clipsToBounds = true
let xPosition = self.imagesScrollView.frame.width * CGFloat(i)
imageview.frame = CGRect(x: xPosition, y: 0, width: self.imagesScrollView.frame.width, height: self.imagesScrollView.frame.height)
print(imageview)
imagesScrollView.addSubview(imageview)
}
let scrollingTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.newStartScrolling), userInfo: nil, repeats: true)
scrollingTimer.fire()
}
func newStartScrolling()
{
if ViewController.i == imagesArray.count {
ViewController.i = 0
}
let x = CGFloat(ViewController.i) * imagesScrollView.frame.size.width
imagesScrollView.setContentOffset(CGPoint(x: x, y: 0), animated: true)
ViewController.i += 1
}
you have to use func setContentOffset(_ contentOffset: CGPoint, animated: Bool) method to change content offset using animation.
#IBOutlet weak var imageView:UIImageView!
var i=Int()
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(imageChange), userInfo: nil, repeats: true)
// Do any additional setup after loading the view.
}
#objc func imageChange(){
self.imageView.image=images[i]
if i<images.count-1{
i+=1
}
else{
i=0
}
}
I need to preform username and login checks upon pressing the login button. I need to do all of this with programmatically. Anyhow, my problem is that when I create a button that connects to a function, the textfields are then out of scope.
import UIKit
class ViewController: UIViewController {
var usernameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let usernameTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
usernameTextField.center = CGPoint(x: 160, y: 80)
usernameTextField.placeholder = "username"
usernameTextField.text = ""
usernameTextField.borderStyle = UITextBorderStyle.line
usernameTextField.backgroundColor = UIColor.white
usernameTextField.textColor = UIColor.blue
self.view.addSubview(usernameTextField)
let button = UIButton(type: UIButtonType.system) as UIButton
let xPostion:CGFloat = 10
let yPostion:CGFloat = 200
let buttonWidth:CGFloat = 150
let buttonHeight:CGFloat = 45
button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)
button.backgroundColor = UIColor.lightGray
button.setTitle("Submit", for: UIControlState.normal)
button.tintColor = UIColor.black
button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(_ sender:UIButton!) {
let username = usernameTextField.text
print("Username value is \(String(describing: username))!")
print("Button tapped")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
How can I get a usernameTextField at buttonAction function ?
usernameTextField is not out of scope, your app will just crash since you have hidden the property of that name with a local variable inside viewDidLoad.
You should change your let-line to usernameTextField = which does not create a local variable of the same name but assigns something to the property instead:
override func viewDidLoad() {
super.viewDidLoad()
usernameTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
usernameTextField.center = CGPoint(x: 160, y: 80)
usernameTextField.placeholder = "username"
usernameTextField.text = ""
usernameTextField.borderStyle = UITextBorderStyle.line
usernameTextField.backgroundColor = UIColor.white
usernameTextField.textColor = UIColor.blue
self.view.addSubview(usernameTextField)
...
}
I have a simple test application and I want to pan an image inside its view. It will not pan or zoom and I can't see what's wrong with my code.
I have followed this tutorial but implemented it in code. I've made the image width the same as the height so I can pan without necessarily zooming.
Here is my code
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
let scrollView: UIScrollView = {
let scrollView = UIScrollView()
return scrollView
}()
let zoomImageView: UIImageView = {
let imageView = UIImageView()
imageView.isUserInteractionEnabled = true
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.image = #imageLiteral(resourceName: "lighthouse")
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let screenSize = UIScreen.main.bounds
let screenHeight = screenSize.height
scrollView.frame = CGRect(x:0, y:0, width: screenHeight, height: screenHeight)
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 3.0
zoomImageView.frame = CGRect(x:0, y:0, width: screenHeight, height: screenHeight)
scrollView.addSubview(self.zoomImageView)
view.addSubview(scrollView)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomImageView
}
}
Search in your code for the term contentSize. You don't see it, do you? But the most fundamental fact about how a scroll view works is this: a scroll view without a contentSize cannot scroll (i.e. "pan" as you put it). In particular, it must have a content size larger than its own bounds size in order to be able to scroll along that axis (height or width, or both). Otherwise, there is nothing to scroll.
How can I create an animation like this one?
override func draw(_ rect: CGRect)
{
let xPointRect = viewWithTag(1)?.alignmentRect(forFrame: rect).midX
let yPointRect = viewWithTag(1)?.alignmentRect(forFrame: rect).midY
let widthSize = self.viewWithTag(1)?.frame.size.width
let heightSize = self.viewWithTag(1)?.frame.size.height
let sizeRect = CGSize(width: widthSize! * 0.8, height: heightSize! * 0.4)
let rectPlacementX = CGFloat(sizeRect.width/2)
let rectPlacementY = CGFloat(sizeRect.height/2)
let context2 = UIGraphicsGetCurrentContext()
context2?.setLineWidth(2.0)
context2?.setStrokeColor(UIColor.red.cgColor)
context2?.move(to: CGPoint(x: (xPointRect! - rectPlacementX), y: (yPointRect! - rectPlacementY)))
context2?.addLine(to: CGPoint(x: (xPointRect! + rectPlacementX), y: (yPointRect! + rectPlacementY)))
context2?.setLineDash(phase: 3, lengths: dashArray)
context2?.strokePath()
context2.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 1.0,
delay: 0,
usingSpringWithDamping: 0.15,
initialSpringVelocity: 6.0,
options: .allowUserInteraction,
animations: { context2.transform = CGAffineTransform.identity },
completion: nil)
}
My current code is not working because context2 doesn't contain a member .transfer since it is a CGRect.
How can I make this line animate? Any idea?
A CGRect is not visible, so I do not see why you want to animate it.
I assume what you want to animate the frame of a UIView.
You can change many properties of a UIView in an animation block. Also it's frame:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
someParentView.addSubview(view)
UIView.animate(withDuration: 2.5) {
someUIView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
}