UIImageview Programmatically in swift - cocoa-touch

I'm just trying to create a UIImage View programmatically, I have a new view and I tried doing this
let imageName = "yourImage.png"
view.backgroundColor = UIColor.colorWithPatternImage(UIImage(named:imageName))
This code doesn't work. please help me as soon as possible

This is for image with 100 height and 100 width:
var imageViewObject :UIImageView
imageViewObject = UIImageView(frame:CGRectMake(0, 0, 100, 100));
imageViewObject.image = UIImage(named:"imageName.png")
self.view.addSubview(imageViewObject)
To resize the image to fit the view frame:
imageViewObject.contentMode = UIViewContentMode.ScaleToFill
or
imageViewObject.contentMode = UIViewContentMode.ScaleAspectFit
or
imageViewObject.contentMode = UIViewContentMode.ScaleAspectFill

First create UIImageView , add image in UIImageView with frame and than give image Name.The following code help you.
var imageView : UIImageView
imageView = UIImageView(frame:CGRectMake(10, 50, 100, 300));
imageView.image = UIImage(named:"image.jpg")
self.view.addSubview(imageView)

Related

UIImage with resizableImageWithCapInsets Does Not Respond in Dark Mode

Does anyone know of a way to make a UIImage that has been stretched with resizableImageWithCapInsets respond to changes in light/dark mode? My current implementation only takes into consideration dark/light mode when it is being drawn the first time.
[thumbnailContainer addSubview:[self addTileBackgroundOfSize:thumbnailContainer.bounds]];
- (UIImageView *) addTileBackgroundOfSize:(CGRect)bounds {
UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:bounds];
UIEdgeInsets insets = UIEdgeInsetsMake(10.0f, 49.0f, 49.0f, 10.0f);
UIImage *backgroundImage = [[UIImage imageNamed:#"UnivGalleryTile"] resizableImageWithCapInsets:insets];
backgroundView.image = backgroundImage;
return backgroundView;
}
I guess I could redraw them in a traitCollection delegate method but I was hoping there is a better way to make them respond.
First of all, there is no surprise here. When you say resizableImage, you make a new image. It is no longer the image you got from the asset catalog, so it has lost the automatic linkage / dynamism that makes an image change automatically to another image when the trait collection changes.
Second, that doesn't matter, because you can create that linkage with any two images (that are not in the asset catalog). You do that by way of the UIImageAsset class.
So here's a working example. Imagine that Faces is the name of a pair in the asset catalog, one for Any, one for Dark. I'll extract each member of the pair, apply resizable to each one, and then join the new pair together as variants of one another:
let tclight = UITraitCollection(userInterfaceStyle: .light)
let tcdark = UITraitCollection(userInterfaceStyle: .dark)
var smiley = UIImage(named: "Faces", in: nil, compatibleWith: tclight)!
var frowney = UIImage(named: "Faces", in: nil, compatibleWith: tcdark)!
let link = UIImageAsset()
let insets = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
smiley = smiley.resizableImage(withCapInsets: insets)
frowney = frowney.resizableImage(withCapInsets: insets)
link.register(smiley, with: tclight)
link.register(frowney, with: tcdark)
Or in Objective-C:
UITraitCollection* tclight = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight];
UITraitCollection* tcdark = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];
UIImage* smiley = [UIImage imageNamed:#"Faces" inBundle:nil compatibleWithTraitCollection:tclight];
UIImage* frowney = [UIImage imageNamed:#"Faces" inBundle:nil compatibleWithTraitCollection:tcdark];
UIImageAsset* link = [UIImageAsset new];
UIEdgeInsets insets = UIEdgeInsetsMake(30, 30, 30, 30);
smiley = [smiley resizableImageWithCapInsets:insets];
frowney = [frowney resizableImageWithCapInsets:insets];
[link registerImage:smiley withTraitCollection:tclight];
[link registerImage:frowney withTraitCollection:tcdark];
All done. Notice that in the code there is no need to retain any of the objects (link, smiley, frowney).
Now if you insert one member of the pair into, say, an image view, it will change to the other automatically when the user light/dark mode changes:
let tc = self.traitCollection
let im = link.image(with: tc)
self.imageView.image = im
I'll switch back and forth between light and dark mode to prove that this is working:
I have solved it, but boy is this ugly. So, if anyone has a nicer solution I am open to it:
I first store the image view in an NSMutableArray:
- (UIImageView *) addTileBackgroundOfSize:(CGRect)bounds {
UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:bounds];
UIEdgeInsets insets = UIEdgeInsetsMake(10.0f, 49.0f, 49.0f, 10.0f);
UIImage *backgroundImage = [[UIImage imageNamed:#"UnivGalleryTile"] resizableImageWithCapInsets:insets];
backgroundView.image = backgroundImage;
// Store image for re-drawing upon dark/light mode change
[thumbnailArray addObject:backgroundView];
return backgroundView;
}
And then I reset the background image manually when the user changes the screen mode:
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
for (int i = 0; thumbnailArray.count > i; i++) {
UIEdgeInsets insets = UIEdgeInsetsMake(10.0f, 49.0f, 49.0f, 10.0f);
UIImage *backgroundImage = [[UIImage imageNamed:#"UnivGalleryTile"] resizableImageWithCapInsets:insets];
((UIImageView *)[thumbnailArray objectAtIndex:i]).image = backgroundImage;
}
}
It seems resizableImageWithCapsInsets causes the image to lose its dynamic, auto-adapting properties. You could maybe try to create images for both appearances and put them together again into a dynamic image. Check out this gist on how this could be done.
In case of a .tiled image with .zero insets - there's a UIKit bug that removed the configuration, as it only checks for non-zero insets, and does not take into account a case of zero insets with tiled configuration.
A workaround is to do:
let responsiveZeroEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0000001)
let darkImage = yourDarkImage.resizableImage(withCapInsets: responsiveZeroEdgeInsets, resizingMode: .tile)
let lightImage = yourLightImage.resizableImage(withCapInsets: responsiveZeroEdgeInsets, resizingMode: .tile)
And then put them into the asset.
The trick is to use 0.0000001 insets.
I've opened a bug report with Apple: #9997202.

Generate texture UIImage from small image in Swift

I want to create a full size texture image lets say 1000 x 1000 from existing UIImage of size 40 x 40.
The code I am using to create the image is
let textureImg = UIImage(CGImage: CGImageCreateWithImageInRect(textureImage?.CGImage, CGRect(origin: CGPointZero, size: CGSizeMake(1000, 1000)))!)
where textureImage is some image in 40x40.
Please let me know any correct method to achieve this as the code above not giving proper result. The whole image comes white.
Here's how to use CIAffineTile to tile a 40x40 image into a 500x500 one. Be aware, I'm doing some unneeded forced unwrapping, etc. because I pulled this from existing code. This is tested.
let inputImage = UIImage(named: "vermont.jpg")
let tiledImage = createTiledImage(inputImage:inputImage!)
print(inputImage!.size) // displays (40.0, 40.0)
print(tiledImage.size) // displays (500.0,500.0)
imageView.image = tiledImage
func createTiledImage(inputImage:UIImage) -> UIImage {
let filter = CIFilter(name: "CIAffineTile")
filter!.setValue(CIImage(image: inputImage), forKey: "inputImage")
let outputImage = filter?.outputImage?.applyingFilter("CIAffineTile", withInputParameters: nil).cropping(to: CGRect(x: 0, y: 0, width: 500, height: 500))
let ciCtx = CIContext(options: nil)
let cgimg = ciCtx.createCGImage(outputImage!, from: (outputImage?.extent)!)
return UIImage(cgImage: cgimg!)
}

auto-resize a XIB file to be as the screen size

I have a View Controller which has a scrollView embedded inside. In this Scroll view I have adding 4 views which are XIB file views. The XIB files size are 'Inferred' although appear to be iphone5 sizing. When loaded they are not auto-resizing to be the size of the screen, they are staying at iphone5 size.
How can I make the XIB file be the same size as the screen it is loading into?
EDIT:
I have also tried changing the the size of the nib files through the code like this:
// 1) Create the three views used in the swipe container view
let AVc :AViewController = AViewController(nibName: "AViewController", bundle: nil);
let BVc :BViewController = BViewController(nibName: "BViewController", bundle: nil);
let CVc :CViewController = CViewController(nibName: "CViewController", bundle: nil);
let DVc :DViewController = DViewController(nibName: "DViewController", bundle: nil);
AVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
BVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
CVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
DVc.view.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height)
// 2) Add in each view to the container view hierarchy
// Add them in opposite order since the view hieracrhy is a stack
self.addChildViewController(DVc);
self.scrollView!.addSubview(DVc.view);
DVc.didMoveToParentViewController(self);
self.addChildViewController(CVc);
self.scrollView!.addSubview(CVc.view);
CVc.didMoveToParentViewController(self);
self.addChildViewController(BVc);
self.scrollView!.addSubview(BVc.view);
BVc.didMoveToParentViewController(self);
self.addChildViewController(AVc);
self.scrollView!.addSubview(AVc.view);
AVc.didMoveToParentViewController(self);
This still has no affect and it loads the wrong size.
I suggest you to use size classes and then apply the necessary constants at first it'll be a little difficult but by time you'll learn how to apply the size classes and constants.
Here are the links where you'll find the best examples.
If you are not using Auto-Layout then you can add the four views simply by for loop:
let bounds = UIScreen.mainScreen().bounds
let width = bounds.size.width
let height = bounds.size.height
var yAxis: CGFloat = 0.0
for i in 0...3 {
let rect: CGRect = CGRectMake(0, yAxis, width, height)
swift i {
case 0:
view1.frame = rect
case 1:
view2.frame = rect
case 2:
view3.frame = rect
case 3:
view4.frame = rect
default:
break
}
yAxis = yAxis + height
}
Where view1, view2, view3 and view4 are your 4 xib views.
Also, set the content size of the scroll view to height yAxis.
Recommended, You should use AutoLayout it will reduce the lines of code.

How do I resize a UIImage without smoothing? [duplicate]

I want to scale up an UIImage in such a way, that the user can see the pixels in the UIImage very sharp. When I put that to an UIImageView and scale the transform matrix up, the UIImage appears antialiased and smoothed.
Is there a way to render in a bigger bitmap context by simply repeating every row and every column to get bigger pixels? How could I do that?
#import <QuartzCore/CALayer.h>
view.layer.magnificationFilter = kCAFilterNearest
When drawing directly into bitmap context, we can use:
CGContextSetInterpolationQuality(myBitmapContext, kCGInterpolationNone);
I found this on CGContextDrawImage very slow on iPhone 4
Swift 5
let image = UIImage(named: "Foo")
let scaledImageSize = image.size.applying(CGAffineTransform(scaleX: 2, y: 2))
UIGraphicsBeginImageContext(scaledImageSize)
let scaledContext = UIGraphicsGetCurrentContext()!
scaledContext.interpolationQuality = .none
image.draw(in: CGRect(origin: .zero, size: scaledImageSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()!
I was also trying this (on a sublayer) and I couldn't get it working, it was still blurry. This is what I had to do:
const CGFloat PIXEL_SCALE = 2;
layer.magnificationFilter = kCAFilterNearest; //Nearest neighbor texture filtering
layer.transform = CATransform3DMakeScale(PIXEL_SCALE, PIXEL_SCALE, 1); //Scale layer up
//Rasterize w/ sufficient resolution to show sharp pixels
layer.shouldRasterize = YES;
layer.rasterizationScale = PIXEL_SCALE;
For UIImage created from CIImage you may use:
imageView.image = UIImage(CIImage: ciImage.imageByApplyingTransform(CGAffineTransformMakeScale(kScale, kScale)))

Image at the top of the tableview

Hey I am making an app that has to show a big image at the top of the grouped tableview, I don't want the image to be in tablecell because it looks stupid that way. I just want the image to float there, but I have no idea how to do it? Thanks!
Use the table view's tableHeaderView property, like this:
UIImageView *topImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"my logo.png"];
topImage.backgroundColor = [UIColor clearColor];
topImage.frame = CGRectMake(0, 0, theTableView.bounds.size.width, 100); // replace 100 with the height of your image, plus a bit if you want it to have a margin
topImage.contentMode = UIViewContentModeCenter;
theTableView.tableHeaderView = topImage;
[topImage release];