Changing Background on orientation change fails - ios

I have two images bg-land and bg-port for different orientation. I wanna change the image on chnaging orientation. But, the image does not change. When I load the Simulator in LandScape, bg-land works perfect but does not work with Rotation. Code:
override func viewDidLoad() {
super.viewDidLoad()
loadBackground()
}
func loadBackground(){
if(UIApplication.sharedApplication().statusBarOrientation.isPortrait){
var bgImage = UIImage(named: "bg-port")
var background = UIImageView(frame: self.view.bounds);
background.image = bgImage
self.view.addSubview(background)
self.view.sendSubviewToBack(background)
println(bgImage)
} else {
var bgImage = UIImage(named: "bg-land")
var background = UIImageView(frame: self.view.bounds);
background.image = bgImage
self.view.addSubview(background)
self.view.sendSubviewToBack(background)
println(bgImage)
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
loadBackground()
}

This code works fine for me try this:
override func viewDidLoad() {
super.viewDidLoad()
self.loadBackground()
}
func loadBackground(){
if(UIApplication.sharedApplication().statusBarOrientation.isPortrait){
let imageName = "Texture.jpg"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = self.view.bounds
view.addSubview(imageView)
} else {
let imageName = "AppIcon.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = self.view.bounds
view.addSubview(imageView)
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
loadBackground()
}
Don't forget to change image name from this code.
May be this will help you.

It's not changing because you are sending the newly added UIImageView to the back of your previously created UIImageView. Instead of doing that, create a member variable in your class for UIImageView. (Name it as background)
func loadBackground()
{
if self.background == nil
{
self.background = UIImageView()
self.view.addSubview(self.background)
self.view.sendSubviewToBack(self.background)
}
if(UIApplication.sharedApplication().statusBarOrientation.isPortrait)
{
var bgImage = UIImage(named: "bg-port")
self.background.frame = self.view.bounds;
self.background.image = bgImage
}
else
{
var bgImage = UIImage(named: "bg-land")
self.background.frame = self.view.bounds;
background.image = bgImage
}
}
But it is better to add a UIImageView outlet to your interface and loading the image using code, rather than creating one at run-time. And I prefer that would be a nice approach.

Related

Transform UIView to UIImage and set it with UIImageView

I refered to this question, and did add extension to UIView:
extension UIView {
// Using a function since `var image` might conflict with an existing variable
// (like on `UIImageView`)
func asImage() -> UIImage {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
} else {
UIGraphicsBeginImageContext(self.frame.size)
self.layer.render(in:UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImage(cgImage: image!.cgImage!)
}
}
}
Then i create very simple test view:
private class FakeTestView: BaseView {
override func prepare() {
backgroundColor = .blue
setup()
}
private func setup(){
let lbl = LabelSL.regular()
lbl.text = "LabelSL.regular()"
addSubview(lbl)
lbl.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
lbl.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
}
That view showing correctly when treated as UIView.
Finally, i tried:
let newSlideFrame = CGRect(x: CGFloat(i) * event.expectedWidth(),
y: 0,
width: event.expectedWidth(),
height: frame.size.height)
let imgView = UIImageView()
imgView.contentMode = .scaleAspectFit
imgView.frame = newSlideFrame
imgView.image = FakeTestView().asImage()
scroll.addSubview(imgView)
But there is nothing showing. Code from above work when i try to add UIView, or UIImageView with sample images.

How to apply an animation effect to UIImageView slideshow

On Swift 3.0 how can I apply some animation effect to this slideshow? Cannot find animation effects related to animationWithDuration method.
let image1 = UIImage(named: "image1")!
let image2 = UIImage(named: "image2")!
let image3 = UIImage(named: "image3")!
var imagesArray : [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
imagesArray = [image1, image2, image3]
myView.clipsToBounds = true
myView.animationImages = imagesArray
myView.animationDuration = 10.0
myView.animationRepeatCount = 0
myView.startAnimating()
}
It looks like you are using the build in frame animation for UIImageView. This is designed to just cycle through the images, like an animated gif. It doesn't really have more sophisticated animation than that. What you can do if you want transition effects is alternate between two image views and use the UIView Animation methods to switch between them. This just does a crossfade by manipulating alpha:
var images = [UIImage]()
var currentImageindex = 0
func animateImageViews() {
swap(&firstImageView, &secondImageView)
secondImageView.image = images[currentImageindex]
currentImageindex = (currentImageindex + 1) % images.count
UIView.animate(withDuration: 1, animations: {
self.firstImageView.alpha = 0
self.secondImageView.alpha = 1
}, completion: { _ in
self.animateImageViews()
})
}
Here is playground that shows how it works. You need to drop 2 images into the resources folder named 1.png and 2.png for it to work. Note that setting the view frames like this is horrible programming practice i just did it here for brevity. use interface builder and autolayout in your actual code.
import PlaygroundSupport
import UIKit
class Demo: UIViewController {
let button = UIButton()
var firstImageView = UIImageView()
var secondImageView = UIImageView()
var images = [UIImage]()
var currentImageindex = 0
override func viewDidLoad() {
view.addSubview(firstImageView)
view.addSubview(secondImageView)
images.append(UIImage(named: "1.png")!)
images.append(UIImage(named: "2.png")!)
firstImageView.image = images[0]
secondImageView.image = images[1]
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
firstImageView.frame = view.frame
secondImageView.frame = view.frame
}
override func viewDidAppear(_ animated: Bool) {
animateImageViews()
}
func animateImageViews() {
swap(&firstImageView, &secondImageView)
secondImageView.image = images[currentImageindex]
currentImageindex = (currentImageindex + 1) % images.count
UIView.animate(withDuration: 1, animations: {
self.firstImageView.alpha = 0
self.secondImageView.alpha = 1
}, completion: { _ in
self.animateImageViews()
})
}
}
let viewcontroller = Demo()
viewcontroller.view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
PlaygroundPage.current.liveView = viewcontroller.view

Swift Image masking

Trying to achieve something like below picture. Where the image has a mask to display certain portion of the image. Here is the code to create the shape
let shape = CAShapeLayer()
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
let path = UIBezierPath()
path.moveToPoint(CGPointMake(0 , 0))
path.addLineToPoint(CGPointMake(200, 0))
path.addLineToPoint(CGPointMake(160, 200))
path.addLineToPoint(CGPointMake(0, 200))
path.closePath()
shape.path = path.CGPath
Is there a way to add image into this layer. so its bound are set respective to the shape? BEFORE/AFTER image can be ignored.
Any leads would be appreciated. Thanks!
This is the solution I came up with. You need to have proper mask image.
import UIKit
import SnapKit
class TestScreenController: UIViewController {
let beforeView = UIImageView()
let afterView = UIImageView()
let maskView = UIImageView()
let divider = UIImageView(image: UIImage(named: "before_after_image"))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setup(){
self.view.addSubview(maskView)
self.maskView.addSubview(beforeView)
self.maskView.addSubview(afterView)
self.maskView.addSubview(divider)
maskView.snp_makeConstraints { (make) in
make.top.equalTo(self.view).offset(50)
make.width.equalTo(300)
make.height.equalTo(110)
make.centerX.equalTo(self.view)
}
maskView.layer.cornerRadius = 15
maskView.layer.masksToBounds = true
let image = UIImage(named: "beforeWash-min.png")
let maskingImage = UIImage(named: "beforeImageM-1")
beforeView.image = maskImage(image!, mask: maskingImage!)
beforeView.contentMode = .ScaleToFill
beforeView.snp_makeConstraints { (make) in
make.top.left.height.equalTo(self.maskView)
make.width.equalTo(self.maskView).multipliedBy(0.50).offset(12)
}
let imageA = UIImage(named: "afterWash-min.png")
let maskingImageA = UIImage(named: "afterImageM-1")
afterView.image = maskImage(imageA!, mask: maskingImageA!)
afterView.contentMode = .ScaleToFill
afterView.snp_makeConstraints { (make) in
make.top.right.height.equalTo(self.maskView)
make.width.equalTo(self.maskView).multipliedBy(0.50).offset(10)
}
divider.snp_makeConstraints { (make) in
make.center.equalTo(maskView)
make.height.equalTo(maskView)
}
}
func maskImage(image:UIImage, mask:(UIImage))->UIImage{
let imageReference = image.CGImage
let maskReference = mask.CGImage
let imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),
CGImageGetHeight(maskReference),
CGImageGetBitsPerComponent(maskReference),
CGImageGetBitsPerPixel(maskReference),
CGImageGetBytesPerRow(maskReference),
CGImageGetDataProvider(maskReference), nil, true)
let maskedReference = CGImageCreateWithMask(imageReference, imageMask)
let maskedImage = UIImage(CGImage:maskedReference!)
return maskedImage
}
}

nil in UIPageControl view subview

I'm new in ios swift and want to change UIPageControl dots size via images.
I found same issue here (UIPageControl custom class - found nil changing image to the dots)
but seems the answer is wrong, still in page control view subviews(UIImageView) is nil
As I don't have enough reputation have to ask here.
here how I'm adding image views to the scroll view
let imgOne = UIImageView(frame: CGRectMake(0, 0,scrollViewWidth, scrollViewHeight))
imgOne.image = UIImage(named: "1")
let imgTwo = UIImageView(frame: CGRectMake(scrollViewWidth, 0,scrollViewWidth, scrollViewHeight))
imgTwo.image = UIImage(named: "2")
let imgThree = UIImageView(frame: CGRectMake(scrollViewWidth*2, 0,scrollViewWidth, scrollViewHeight))
imgThree.image = UIImage(named: "3")
let imgFour = UIImageView(frame: CGRectMake(scrollViewWidth*3, 0,scrollViewWidth, scrollViewHeight))
imgFour.image = UIImage(named: "4")
self.scrollView.addSubview(imgOne)
self.scrollView.addSubview(imgTwo)
self.scrollView.addSubview(imgThree)
self.scrollView.addSubview(imgFour)
and below the answer to the problem
class PageControl: UIPageControl {
var activeImage: UIImage!
var inactiveImage: UIImage!
override var currentPage: Int {
willSet {
self.updateDots()
}
}
convenience init(activeImage: UIImage, inactiveImage: UIImage) {
self.init()
self.activeImage = activeImage
self.inactiveImage = inactiveImage
self.pageIndicatorTintColor = UIColor.clearColor()
self.currentPageIndicatorTintColor = UIColor.clearColor()
}
func updateDots() {
for var i = 0; i < count(subviews); i++ {
var view: UIView = subviews[i] as! UIView
if count(view.subviews) == 0 {
self.addImageViewOnDotView(view, imageSize: activeImage.size)
}
var imageView: UIImageView = view.subviews.first as! UIImageView // nil
imageView.image = self.currentPage == i ? activeImage : inactiveImage
}
}
// MARK: - Private
func addImageViewOnDotView(view: UIView, imageSize: CGSize) {
var frame = view.frame
frame.origin = CGPointZero
frame.size = imageSize
var imageView = UIImageView(frame: frame)
imageView.contentMode = UIViewContentMode.Center
view.addSubview(imageView)
}
}
Spending few days I solved it in the following way...
Don't know how is good the solution, feel free to to improve...
There was 2 problems
1: in function updateDots, should look like this
func updateDots() {
for var i = 0; i < subviews.count; i++ {
var imageView: UIImageView? = nil
let view: UIView = subviews[i]
if (view.subviews.first is UIImageView) {
if (subviews.count == 0) {
addImageViewOnDotView(view, imageSize: activeImage.size)
}
imageView = (view.subviews.first as! UIImageView)
imageView!.image = self.currentPage == i ? activeImage : inactiveImage
}
if (imageView == nil) {
imageView = UIImageView(frame: CGRectMake(0.0, 0.0, view.frame.size.width, view.frame.size.height));
imageView!.image = self.currentPage == i ? activeImage : inactiveImage
view.addSubview(imageView!)
}
}
}
2: When call this function, should be after (didSet) scroll not before (willSet)
override var currentPage: Int {
didSet {
self.updateDots()
}
}

Hide subview image once the view has loaded (using Swift)

Technologies: XCode6, iOS 8.2, Swift
When the view loads, I add an image:
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.navigationController?.toolbarHidden = false;
openLoadingPopup()
if browserHistory.count < 1 {
backButton.enabled = false
}
let imageName = UIImage(named: "image.png")
let imageview = UIImageView(image: imageName)
imageview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.view.addSubview(imageview)
}
And I want to remove that image here (if possible). Best way to do that?
func webViewDidFinishLoad(webView: UIWebView) {
UIApplication.sharedApplication()
. networkActivityIndicatorVisible = false
closeLoadingPopup()
if cacheURL {
++browserHistoryIndex
browserHistory.insert(webView.request!.URL, atIndex: browserHistoryIndex)
backButton.enabled = browserHistoryIndex != 0
//forwardButton.enabled = browserHistoryIndex != browserHistory.count - 1
}
if webView.request!.URL == lastURL {
cacheURL = true
}
}
Make imageView a property instead of a local variable, and use imageView.removeFromSuperview() in the webViewDidFinishLoad method.

Resources