How to make an animation on an ImageView in android? - android-animation

I have problem with my code of making a rotation animation on an ImageView. My ImageView is in service not in an activity.
ImageView myImage = new ImageView(this);
final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotator);
myImage.startAnimation(myRotation);
My XML rotation:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="4000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="90"
android:toYScale="0.0" />
I have tried this successfully if the ImageView looks like:
ImageView myImage = (ImageView)findViewById(R.id.imageView1);
Instead of: ImageView myImage = new ImageView(this);
However, I have to choice to initialize myImage = new ImageView(this);
So, is there any trick to make my ImageView rotatable?

Related

UIImageView.image bigger than UIImageView

I have a UIImageView in a custom tableview cell. When I set the UIimageview property, the uiimageview.image is bigger than the uiimageview. Why?
Here is the code:
cell.imageView.image=[UIImage imageNamed:#"BlueMooseLogo.png"];
And here is a link to what the cell looks like. The blue square is the background of the imageview, and the blue moose is the image.
https://docs.google.com/document/d/1G7BYCriYbSGYHryP5OI7XHuVpqRKiNcBrxdY14wDgoA/edit?usp=sharing
If it's relevant, within interface builder, after I select the uiimageview, I have the view set to scale to fill.
I've faced the same problem, and tried a lot ways to fix it, finally, I did it. When you try to assign the image to your UIImageView, please resize your image as a thumbnail image, and use this thumbnail image to display. The following code just for your reference.
static func resizeImage(image:UIImage, toTheSize size:CGSize) -> UIImage{
let scale = CGFloat(max(size.width/image.size.width,
size.height/image.size.height))
let width:CGFloat = image.size.width * scale
let height:CGFloat = image.size.height * scale;
let rr:CGRect = CGRectMake( 0, 0, width, height);
UIGraphicsBeginImageContextWithOptions(size, false, 0);
image.drawInRect(rr)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage
}
You most likely want the content mode to be "Aspect Fit" not "Aspect Fill".
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
I think that it would be a clip subviews issue.
Check your UIImageView property.
Storyboard : check clip subviews in Attributes inspector
Code : imgView.clipsToBounds = YES

Drawing a background with a pattern in sprite kit

-(void)startNewScene{
[self removeAllChildren];//Clear
NSImage *image=[NSImage imageNamed:#"down"];
//image.size=CGSizeMake(self.barWidth*2, self.frame.size.height);
NSColor *color=[NSColor colorWithPatternImage:[NSImage imageNamed:#"down"]];
SKSpriteNode *sprite= [SKSpriteNode spriteNodeWithColor:color size:CGSizeMake(200, 300)];
sprite.position=CGPointMake(10, CGRectGetMidY(self.frame));
SKAction *move=[SKAction moveToX:self.frame.size.width duration:1];
SKAction *goBack= [SKAction moveToX:-self.barWidth duration:0];
SKAction *action=[SKAction sequence:#[move,goBack]];
[sprite runAction:[SKAction repeatActionForever:action]];
[self addChild:sprite];
}
Hi everybody, i want to make a node with a pattern color which is an image but this code doesn't work at all.
I've tried with 3 different images in 3 different formats so i think that's not the problem.
I know that the variable image is useless but i've used it to understand if the nsimage was the problem. When i look for the value of image whit a breakpoint it has been created, but its width and height are both 0.
I really can't understand why this doesn't work at all (the node doesn't show up).
Sprite Kit nodes with a color property don't support colors using a pattern image. It has to be a solid color, for example one you'd create with colorWithRed:green:blue:alpha:.
You should create your pattern image in an image program and add it to the bundle. If you make the pattern image grayscale you can colorize it at runtime to create various color combinations. For example a checkerboard white/black pattern image and the sprite node's color set to red will give you a black & red pattern. Adjust the sprite node's colorBlendFactor to control the "brightness" of the color component.
Here is a link describes how to draw a background with a pattern image
I've made some changes in my Swift's SKScene version:
override func didMoveToView(view: SKView) {
let bkg = UIImage(named: "Background")
let backgroundCGImage = bkg!.CGImage //change the string to your image name
let coverageSize = self.size //the size of the entire image you want tiled
let textureSize = CGRectMake(0, 0, bkg!.size.width, bkg!.size.height); //the size of the tile.
UIGraphicsBeginImageContextWithOptions(coverageSize, false, UIScreen.mainScreen().scale);
let context = UIGraphicsGetCurrentContext()
CGContextDrawTiledImage(context, textureSize, backgroundCGImage)
let tiledBackground = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let backgroundTexture = SKTexture(image: tiledBackground)
let backgroundTiles = SKSpriteNode(texture: backgroundTexture)
backgroundTiles.yScale = -1 //upon closer inspection, I noticed my source tile was flipped vertically, so this just flipped it back.
backgroundTiles.position = CGPointMake(self.size.width/2, self.size.height/2)
self.addChild(backgroundTiles)
}

Using cornerRadius on a UIImageView in a UITableViewCell

I'm using a UIImageView for each of my UITableViewCells, as thumbnails. My code uses SDWebImage to asynchronously grab those images from my backend and load them in, and then caching them. This is working fine.
My UIImageView is a 50x50 square, created in Interface Builder. Its background is opaque, white color (same as my UITableViewCell background color, for performance). However, I'd like to use smooth corners for better aesthetics. If I do this:
UIImageView *itemImageView = (UIImageView *)[cell viewWithTag:100];
itemImageView.layer.cornerRadius = 2.5f;
itemImageView.layer.masksToBounds = NO;
itemImageView.clipsToBounds = YES;
My tableview drops around 5-6 frames immediately, capping about 56 FPS during fast scrolling (which is okay), but when I drag and pull the refresh control, it lags a bit and drops to around 40 FPS. If I remove the cornerRadius line, all is fine and no lag. This has been tested on an iPod touch 5G using Instruments.
Is there any other way I could have a rounded UIImageView for my cells and not suffer a performance hit? I'd already optimized my cellForRowAtIndexPath and I get 56-59 FPS while fast scrolling with no cornerRadius.
Yes, that's because cornerRadius and clipToBounds requires offscreen rendering, I suggest you to read these answer from one of my question. I also quote two WWDC session thatyou should see. The best thing you can do is grab the image right after is downloaded and on another thread dispatch a method that round the images. Is preferable that you work on the image instead of the imageview.
// Get your image somehow
UIImage *image = [UIImage imageNamed:#"image.jpg"];
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
cornerRadius:10.0] addClip];
// Draw your image
[image drawInRect:imageView.bounds];
// Get the image, here setting the UIImageView image
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
Method grabbed here
You can also subclass the tableviewcell and override the drawRect method.
The dirty but very effective way is draw a mask in photoshop with inside alpha and around the matching color of the background of the cell and add another imageView, not opaque with clear background color, on the one with images.
There is another good solution for this. I did it a few times in my projects. If you want to create a rounded corners or something else you could just use a cover image in front of your main image.
For example, you want to make rounded corners. In this case you need a square image layer with a cut out circle in the center.
By using this method you will get 60fps on scrolling inside UITableView or UICollectionView. Because this method not required offscreen rendering for customizing UIImageView's (like avatars and etc.).
Non blocking solution
As a follow up to Andrea's response, here is a function that will run his code in the background.
+ (void)roundedImage:(UIImage *)image
completion:(void (^)(UIImage *image))completion {
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
CGRect rect = CGRectMake(0, 0, image.size.width,image.size.height);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:rect
cornerRadius:image.size.width/2] addClip];
// Draw your image
[image drawInRect:rect];
// Get the image, here setting the UIImageView image
UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
dispatch_async( dispatch_get_main_queue(), ^{
if (completion) {
completion(roundedImage);
}
});
});
}
Swift 3 version of thedeveloper3124's answer
func roundedImage(image: UIImage, completion: #escaping ((UIImage?)->(Void))) {
DispatchQueue.global().async {
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
// Add a clip before drawing anything, in the shape of an rounded rect
UIBezierPath(roundedRect: rect, cornerRadius: image.size.width/2).addClip()
// Draw your image
image.draw(in: rect)
// Get the image, here setting the UIImageView image
guard let roundedImage = UIGraphicsGetImageFromCurrentImageContext() else {
print("UIGraphicsGetImageFromCurrentImageContext failed")
completion(nil)
return
}
// Lets forget about that we were drawing
UIGraphicsEndImageContext()
DispatchQueue.main.async {
completion(roundedImage)
}
}
}

Draw bezier curve above image of UIImageView

How to draw beziercurve above the image of the UIImageView. I am subclassing UIImageView and drawing circles using UIBezierCurve on the corners of image view. But as soon as i place the image in UIImageView the inside part of circles are overlapped by the image. So is there any solution which lets me draw the UIBezier path on the UIimage of uiimageview ?
You can try subclassing simple UIView and drawing an image yourself using drawInRect: method of UIImage instance. It should look something like this:
- (void)drawRect:(CGRect)dirtyRect {
// note you can get image from anywhere
UIImage *image = [UIImage imageNamed:#"MyImage"];
[image drawInRect:self.bounds];
// now that image is drawn, everything
// past this point will be drawn on top of it
...
}

"BackgroundMoving" Code is not Working in iPhone4S

I am making one game in which i am facing problem when I test my App on Device(iPhone4) the background of it is not working. Like when background image ends BLACKISH BACKGROUND COLOR comes. My Background image size is 460X2880,image name "mars_sample.jpg" (for iPhone4) And code for Background Moving is :
-(void)backgroundmoving:(ccTime)dt
{
static float bk_f=0.0f;
bk_f -=0.9;
if (bk_f <= -960*3) {bk_f=0;}
background.position = ccp( 0,bk_f);
}
When I am loading "460X2880" size image as Background image then it doesn't loads in background AND if it is like of size "460X1192" it loads image in background but Showing BLACKISH BACKGROUND Color on Top of screen.
Below one CODE is for Setting Background image :
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
background = [CCSprite spriteWithFile:#"staripad.png"];
background.anchorPoint= ccp(0,0);
[self addChild:background z:0];
} else {
background = [CCSprite spriteWithFile:#"mars_sample.jpg"];
background.anchorPoint= ccp(0,0);
[self addChild:background z:0];
[self schedule:#selector(backgroundmoving:) interval:1/30];
}
Please Give me some suggestions, how it will work.
Thanks ALL
Regards,
Tauseef Khan
Check background.position = ccp( 0, bk_f ) in backgroundmoving you are setting the Y value of the coordinate to a fixed value, bk_f. I assume that it's the X value that you'd want to change in order to scroll the background image, background.position = ccp( bk_f, 0 ).
The parameter dt to backgroundmoving that I assume is to provide a moving background image is not used.
Make sure that the background view is set to expand to fit it's super view using autosize properties .
Examine the origin in the frame property of your background view - check that it is at the top of your screen.
I'd add a plain UIView behind your background UIImageView and set it's color to green or some other harsh color. That way you could visually confirm the real-estate covered by the views.
//in .h file int bk_f=240;
-(void)backgroundmoving:(ccTime)dt
{
bk_f=bk_f-5;
if(bk_f<=0)
{
background.position = ccp( 240,160);
bk_f=240;
}
else
{
background.position = ccp( bk_f,160);
}
}