I'm trying to create some composite UIImage objects with this code:
someImageView.image = [ImageMaker coolImage];
ImageMaker:
- (UIImage*)coolImage {
UIView *composite = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"coolImage"]]; //This is a valid image - can be viewed when debugger stops here
[composite addSubview:imgView];
UIView *snapshotView = [composite snapshotViewAfterScreenUpdates:YES];
//at this point snapshotView is just a blank image
UIImage *img = [self imageFromView:snapshotView];
return img;
}
- (UIImage *)imageFromView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
I just get back a blank black image. How can I fix?
Supplying YES for -snapshotViewAfterScreenUpdates: means it needs a trip back to the runloop to actually draw the image. If you supply NO, it will try immediately, but if your view is off screen or otherwise hasn't yet drawn to the screen, the snapshot will be empty.
To reliably get an image:
- (void)withCoolImage:(void (^)(UIImage *))block {
UIView *composite = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"coolImage"]]; //This is a valid image - can be viewed when debugger stops here
[composite addSubview:imgView];
UIView *snapshotView = [composite snapshotViewAfterScreenUpdates:YES];
// give it a chance to update the screen…
dispatch_async(dispatch_get_main_queue(), ^
{
// … and now it'll be a valid snapshot in here
if(block)
{
block([self imageFromView:snapshotView]);
}
});
}
You would use it like this:
[someObject withCoolImage:^(UIImage *image){
[self doSomethingWithImage:image];
}];
The snapshotted view has to be drawn to the screen for a snapshot view to not be blank. In your case, the composite view must have a superview for drawing to work.
However, you should not be using the snapshotting API for this kind of action. It is very inefficient to create a view hierarchy for the sole purpose of creating an image. Instead, use the Core Graphics API's to setup a bitmap image context, perform drawing and get back the result using UIGraphicsGetImageFromCurrentImageContext().
The reason it's only rendering a black rectangle is because you're drawing the view hierarchy of the snapshot view, which is non-existent.
To make it work, you should pass composite as the parameter like so:
- (UIImage*)coolImage {
UIView *composite = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"coolImage"]]
[composite addSubview:imgView];
UIImage *img = [self imageFromView:composite];
// Uncomment if you don't want composite to have imgView as its subview
// [imgView removeFromSuperview];
return img;
}
Related
I have self view with image view:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];
[self setBluredImageView:imageView];
[self addSubview:imageView];
- (UIImage *)takeSnapshotOfView:(UIView *)view
{
CGFloat reductionFactor = 1;
UIGraphicsBeginImageContext(CGSizeMake(view.frame.size.width/reductionFactor, view.frame.size.height/reductionFactor));
[view drawViewHierarchyInRect:CGRectMake(0, 0, view.frame.size.width/reductionFactor, view.frame.size.height/reductionFactor) afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
In method when I want to show my self view over other view I make this:
- (void)showMe; {
AppDelegate* app = [AppDelegate shared];
[app.window addSubview:self];
UIImage *image = [self blurWithImageEffects:[self takeSnapshotOfView:app.window]];
[[self bluredImageView] setImage:image];
[UIView animateWithDuration:0.4 animations:^{
[self setAlpha:1.0];
}];
}
So as you can see I want to blur "graphic context" that based on main window view. At first time when I present my self view it works perfect, but then, something like blurred image multiply each other.
So this is image when I just first show my view:
When I present my view few times the blurred image looks like this:
So as you can see each time blurred screenshot is different, but I use the same method for getting screenshot and don't update content of the view controller or other ui parts.
Some methods and image categories found here.
You've created a loop of blurring. When you take the screenshot of the view a second time, the bluredImageView is also in the screenshot. That is why you see the effect multiplied. Try removing it and only capturing the context without the effect, then adding it back
- (UIImage *)takeSnapshotOfView:(UIView *)view
{
//Remove the blured image before taking another screenshot.
[self bluredImageView] removeFromSuperview];
CGFloat reductionFactor = 1;
UIGraphicsBeginImageContext(CGSizeMake(view.frame.size.width/reductionFactor, view.frame.size.height/reductionFactor));
[view drawViewHierarchyInRect:CGRectMake(0, 0, view.frame.size.width/reductionFactor, view.frame.size.height/reductionFactor) afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Add it back now that the effect is done
[self addSubview:[self bluredImageView];
return image;
}
My main app has to do some work in a webview, so I want to keep the launch image up longer while this work takes place. To do this, I created a controller with a UIImageView and I'm loading the Default image up in it:
self.imageView.image = [UIImage imageNamed:"Default"];
// These all tend to fill the screen, but end up distorting the image
//self.imageView.contentMode = UIViewContentModeScaleAspectFill;
//self.imageView.contentMode = UIViewContentModeScaleAspectFit;
//self.imageView.contentMode = UIViewContentModeScaleToFill;
// This keeps the aspect the same, but doesn't fill the screen
self.imageView.contentMode = UIViewContentModeCenter;
This mostly works, except when the real launch image goes away and is replaced with mine, I have two white bars - one at the top and one at the bottom - where the image doesn't completely fill. I've tried to set the contentMode to the various fill/fit's, and even though this has the desired effect of filling the full screen, it stretches and distorts the image slightly.
So what I'm wondering is - what does the launch image do that I'm not doing? How can I replicate the display exactly so that the user can't tell it's a different image?
Like in your project I use a launch image and then in the first UIViewController called I have an UIImageView inside. The image resolution, must be exactly the same as the screen's definition.
The code in the UIViewController is something like this :
CGRect fullFrame = [[UIScreen mainScreen] bounds];
// Img Background
UIImageView *background;
if (fullFrame.size.height <= 480) {
background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image-480h.png"]];
}
else if (fullFrame.size.height <= 568) {
background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image-568h.png"]];
}
else if (fullFrame.size.height <= 668) {
background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image-668h.png"]];
}
else {
background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image-736h.png"]];
}
background = CGRectMake(0, 0, frame.size.width, fullFrame.size.height);
myMainView = [[UIView alloc] initWithFrame:frame];
[myMainView addSubview:background];
self.view = myMainView;
I check the different screen size depending on the iPhone 4, 5, 6 and 6 plus.
I am displaying UIImageViews programmatically. It works fine with the first UIView but when I try to display it on the smaller view, it does not resize.
Can you help me. Thanks in advance
By the way, I have a custom class of my UIView called courtView. I use this class for the two UIView
UIImageView *newImage;
NSSet *ballPosition = [self.startPosition valueForKey:#"ballPosition"];
for (BallPosition *courtPosition in ballPosition) {
PlayerPosition *player = [courtPosition valueForKey:#"playerPosition"];
if ([player.team isEqual: #(1)]) {
newImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Btn_blue.png"]];
}
else if ([player.team isEqual: #(2)]){
newImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Btn_red.png"]];
}
else if ([player.team isEqual: #(0)]){
newImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Ball.png"]];
}
newImage.frame = CGRectFromString([courtPosition valueForKey:#"courtPosition"]);
[self.courtView addSubview:newImage];
}
try this code
UIImage *myImage = [UIImage imageNamed :#"myImage.extension"];
//if ur images are static, if your images are from an array then loop it out write the below inside the loop, make sure myImageView is a class,static component.
CGFloat height = myImage.size.height;
CGFloat width = myImage.size.width;
myImageView.frame = CGRectMake (myImageView.frame.origin.x,myImageView.frame.origin.y,height,width);
myImageView.image = myImage;
Hope this helps
I am working on a view based app, I have set the background image as follows.
.h file:
UIImageView *BackgroundImage;
.m file:
viewdidLoad method:
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BG.png"]];
[[self view] addSubview:BackgroundImage];
[BackgroundImage.superview sendSubviewToBack:BackgroundImage];
and on the rotate method:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BG2.png"]];
[[self view] addSubview:BackgroundImage];
[BackgroundImage.superview sendSubviewToBack:BackgroundImage];
[super viewDidLoad];
}
Using this code I am able to set the background, but on rotation the first loaded image is not removed and the second one is loading just behind the first one, so just half of the image is visible, because of the first image is in front of second one.
Is there is a better way to do this?
OR
How can I just remove the first image and then set the second one?
Please help me to resolve this.
Change your didRotate... method to:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[BackgroundImage removeFromSuperview];
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BG2.png"]];
[[self view] addSubview:BackgroundImage];
}
Notice the [BackgroundImage removeFromSuperview]; line. What we are doing here is whenever the device rotates, you remove the old image view and add another one.
Also please notice that variable names should start with lower case, so BackgroundImage should be backgroundImage. This is to tell them apart from classes' names.
If you change your code like this should to work
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BG.png"]];
[self.view addSubview:BackgroundImage];
[self.view sendSubviewToBack:BackgroundImage];
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[BackgroundImage removeFromSuperview];
BackgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BG2.png"]];
[self.view addSubview:BackgroundImage];
[self.view sendSubviewToBack:BackgroundImage];
[super viewDidLoad];
}
This is because you are initializing the UIImageview again. Better to use same UIImageView that is backgroundImage with different image.
[Background Image set image:[UIImage imageNamed:#"BG2.png"]];
Just set the new image when rotating:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
BackgroundImage.image = [UIImage imageNamed:#"BG2.png"];
}
Your code kept adding new image views when rotating.
How [do stuff] properly in iOS?
Start your ivar names using an underscore and a lowercase letter: _backgroundImage instead of BackgroundImage.
Insert a subview in the right spot: [self.view insertSubview:_backgroundImage atIndex:0];
I am trying to move a UIImage, first button press creates the image and second press moves it.
The image only needs to exist upon pressing the button.
In the simulator it creates the button and places it, the second time it click just doesn't do anything.
This is my Code
- (IBAction) btn:(id)sender {
UIImageView *myImage = [[UIImageView alloc] init];
myImage.image = [UIImage imageNamed:#"keyframe"];
if (startUp == 1){
//Create Image and add to view
myImage.frame = CGRectMake(200, 300, 10, 10);
myImage.image = [UIImage imageNamed:#"keyframe"];
[self.view addSubview:myImage];
//Set startUp to 0 and output rect value
startUp = 0;
NSLog(#"currentFrame %#", NSStringFromCGRect(myImage.frame));
}else if (startUp == 0){
//Change position, size and log to debug
myImage.frame = CGRectMake(500,100 ,20, 20);
NSLog(#"newFrame %#", NSStringFromCGRect(myImage.frame));
}
}
How do you programmatically move a programmatically added UIimage?
I tried changing the center value but that doesn't work either.
Try something like this – tested and working sample:
#import "ViewController.h"
#interface ViewController () {
BOOL startUp;
UIImageView *myImage;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
startUp = YES;
}
- (IBAction)doWork:(id)sender {
if (startUp) {
UIImage *img = [UIImage imageNamed: #"keyframe"];
myImage = [[UIImageView alloc] initWithImage: img];
[myImage sizeToFit];
[myImage setCenter: CGPointMake(200, 300)];
[self.view addSubview: myImage];
startUp = NO;
} else {
[myImage setCenter: CGPointMake(400, 500)];
}
}
#end