Can somebody help me here?. New as iPhone Developer. I am trying to display a .png picture in a circle instead of a rectangle which is the standard for iPhone
Well, all png files are 'rectangles' but if you want to have the apperence of a circle or other non rectangle object on the screen you can do so by using transparacy. To make sure the transparent pixels in the image are also transparent on the iPhone, you can set the background color of the UIImageView to clear. This can be done in Interface Builder by dragging the opacity slider in the background color picker all the way down,
or in code as follows:
UIImage *image = [UIImage imageNamed:#"yourRoundImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.backgroundColor = [UIColor clearColor];
[self.view addSubview: imageView];
If you simply want to add rounder corners, to make a circle, you can also use the cornerRadius Property like this if you have added the QuartzCore framework to your project:
#import <QuartzCore/QuartzCore.h>
UIImage *image = [UIImage imageNamed:#"yourRoundImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.layer.cornerRadius = image.size.width / 2;
imageView.layer.masksToBounds = YES;
[self.view addSubview: imageView];
try this code
yourImageView.layer.cornerRadius = yourImageView.frame.size.height /2;
yourImageView.layer.masksToBounds = YES;
yourImageView.layer.borderWidth = 0;
this show image like ios 7 circle image thanks
My contribution with a swift extension used to set an UIImageView as circle
extension UIImageView{
func asCircle(){
self.layer.cornerRadius = self.frame.width / 2;
self.layer.masksToBounds = true
}
}
Just call MyImageView.asCircle()
Use a UIImageView and set the cornerRadius to be half height and width. view.layer.cornerRadius = cornerRadius;
UIImage rounded corners
Try this to get rounded corners of the image View and also to colour the corners:
self.imgView.layer.cornerRadius =self.imgView.frame.size.height/2;
self.imgView.layer.masksToBounds = YES;
self.imgView.layer.borderColor = [UIColor colorWithRed:148/255. green:79/255. blue:216/255. alpha:1.0].CGColor;
self.imgView.layer.borderWidth=2;
Condition*: The height and the width of the imageView must be same to get rounded corners.
Changing the cornerRadius of the image view works well if you have only a couple of images in your view. However if the image view is in a tableview performance will be affected.
Some of the other options:
Make the image assets circle on the server or manually if they are bundled into the app, with transparent parts for the outer region of the circle.
If the background of the image view doesn't change, create an overlay image that has the inner circle part transparent, and the rest to be the same as the background. Also set the backgroundColor of the image view to clearColor.
When receiving the images, edit them in code to be a circle, in a background thread.
Swift 4: This should display your .png in a circle.
Drag (ctrl + click) an IBOutlet of an image toward your code.
cornerRadius
The radius to use when drawing rounded corners for the layer’s background. Animatable. https://developer.apple.com/documentation/quartzcore/calayer/1410818-cornerradius
clipsToBounds property
A Boolean value that determines whether subviews are confined to the bounds of the view. https://developer.apple.com/documentation/uikit/uiview/1622415-clipstobounds
2.Inside viewDidLoad(), Use the instance property layer.cornerRadius and clipsToBounds.
profileImage.layer.cornerRadius = 50
profileImage.clipsToBounds = true
I'll add a slightly more universal extension to UIImageView that will work with non-square images.
To be noted that it will work slower than the cornerRadius method.
extension UIImageView {
#IBInspectable public var asEllipse:Bool {
get {
if let mask = self.layer.mask {
return mask.name == kMaskLayerName
}
return false;
}
set {
if (newValue) {
let ellipseMask = CAShapeLayer()
ellipseMask.name = kMaskLayerName
ellipseMask.path = CGPathCreateWithEllipseInRect(self.bounds, nil)
ellipseMask.strokeColor = UIColor.clearColor().CGColor
ellipseMask.fillColor = UIColor.whiteColor().CGColor
self.layer.mask = ellipseMask
} else if self.asEllipse {
self.layer.mask = nil
}
}
}
}
private let kMaskLayerName="EllipseMaskLayer"
On Objective-C it looks like:
UIImage* pIconImage = [UIImage imageNamed:#"ImageName"];
UIImageView* pIconView = [[UIImageView alloc] initWithImage:pIconImage];
[pIconView.layer setCornerRadius:pIconImage.size.width / 2];
[pIconView.layer setMasksToBounds:YES];
Related
I'm looking for an easy way to assign to a shape (image.png) that I've got a shade of gray.
i.e depending on a value that I've got ranging from 0 to 1 I would like my shape (image.png) to appear black (value 0) to white (value 1000).
The original color of my shape (image.png) is white.
UIImage *shape = [UIImage imageNamed:#"image.png"];
Thanks in advance
Use UIImageRenderingModeAlwaysTemplate
imageView.image = [[UIImage imageNamed:#"shapeWithTransparancy"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.tintColor = [UIColor colorWithWhite:sliderVal alpha:1.];
You can use masking of CALayer, where you just use another CALayer to crop it.
Create UIView with solid color – the desired shade of gray.
Create CALayer with the image and assign it as a mask.
You can change the background color at any time.
Code:
UIView *imageView = [[UIView alloc] init]; // We call it "image" view ;)
imageView.frame = placeItWhereverYouWant;
CALayer *mask = [CALayer layer];
mask.contents = (__bridge id)[yourImageHere CGImage];
mask.frame = imageView.layer.bounds; // Frame of the mask is sometimes tricky.
imageView.layer.mask = mask;
CGFloat shadeOfGray = 0.7;
imageView.backgroundColor = [UIColor colorWithWhite:shadeOfGray alpha:1];
lets say i have a UIImageView with a frame (0,0,100,30)
.that imageView was assigned an image.
whats the simplest way to show only part of the image?
for example: only what appears in points 30-60 (width) and 0-30 (height). that means that the left and right edges of the image should be hidden.
just to clarify, i don't want to move the view nor change it's size, i just want to hide a subrect of it's frame.
You could always set a mask.
CALayer *maskLayer = [CALayer layer];
maskLayer.backgroundColor = [UIColor blackColor].CGColor;
maskLayer.frame = CGRectmake(30.0, 0.0, 30.0, 30.0);
view.layer.mask = maskLayer;
Masks can be any type of layer, so you could even use a CAShapeLayer for complex masks and do some really cool stuff.
i've found this solution works for me, https://stackoverflow.com/a/39917334/3192115
func mask(withRect rect: CGRect, inverse: Bool = false) {
let path = UIBezierPath(rect: rect)
let maskLayer = CAShapeLayer()
if inverse {
path.append(UIBezierPath(rect: self.view.bounds))
maskLayer.fillRule = kCAFillRuleEvenOdd
}
maskLayer.path = path.cgPath
imageView?.layer.mask = maskLayer
}
I believe masking the image is the best option. But if you were to rotate, transform, animate or want a clear background you can do something like this:
Create a sub view which is the size of the image you want to show. Make sure it has clipsToBounds to true and position the image accordingly.
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
//this is the part of the image you wish to see
UIView *imageWindow = [[UIView alloc] initWithFrame:CGRectMake(30, 0, 30, 30)];
imageWindow.clipsToBounds = YES;
//your image view is the height and width of mainView and x and y is imageWindow - mainView. You can do this manually or put in calculations.
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(imageWindow.frame.origin.x - mainView.frame.origin.x, imageWindow.frame.origin.y - mainView.frame.origin.y, mainView.frame.size.width, mainView.frame.size.height)];
myImage.image = [UIImage imageNamed:#"1024x1024.png"];
[imageWindow addSubview:myImage];
[mainView addSubview:imageWindow];
[self.view addSubview:mainView];
Looking over my code, I don't think mainView is necessary and you could add imageWindow to self.view directly.
I have an UIView and I set a background image in this way:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"sfond-appz.png"]];
My problem is that back-image is not centered inside the view, but it's replayed some times to fill all the view. Is there a way to center image inside uiview and scretch to have screen size?
Note: I can't use UIImageView for background cause I have a scrollview.
You need to process the image beforehand, to make a centered and stretched image.
Try this:
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
For Swift use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)
if let image = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
}else{
UIGraphicsEndImageContext()
debugPrint("Image not available")
}
The colorWithPattern: method is really for generating patterns from images. Thus, the customization you require is most likely not possible, nor is it meant to be.
Indeed you need to use a UIImageView to center and scale an image. The fact that you have a UIScrollView does not prevent this:
Make self.view a generic view, then add both the UIImageView and the UIScrollView as subviews. Make sure all is wired up correctly in Interface Builder, and make the background color of the scroll view transparent.
This is IMHO the simplest and most flexible design for future changes.
Repeat:
UIImage *img = [UIImage imageNamed:#"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];
Stretched
UIImage *img = [UIImage imageNamed:#"bg.png"];
view.layer.contents = img.CGImage;
Correct way to do in Swift 4,
If your frame as screen size is correct then put anywhere otherwise,
important to write this in viewDidLayoutSubviews because we can get actual frame in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
UIGraphicsBeginImageContext(view.frame.size)
UIImage(named: "myImage")?.draw(in: self.view.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
view.backgroundColor = UIColor.init(patternImage: image!)
}
For Swift 2.1 use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
You can use UIGraphicsBeginImageContext method to set the size of image same that of view.
Syntax : void UIGraphicsBeginImageContext(CGSize size);
#define IMAGE(imageName) (UIImage *)[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:imageName ofType:IMAGE_TYPE_PNG]]
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#“MyImage.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:IMAGE(#"mainBg")];
For Swift 3.0 use the following code:
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
The marked answer is fine, but it makes the image stretched.
In my case I had a small tile image that I wanted repeat not stretch.
And the following code was the best way for me to solve the black background issue:
UIImage *tileImage = [UIImage imageNamed:#"myTileImage"];
UIColor *color = [UIColor colorWithPatternImage:tileImage];
UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
[backgroundView setBackgroundColor:color];
//backgroundView.alpha = 0.1; //use this if you want to fade it away.
[self.view addSubview:backgroundView];
[self.view sendSubviewToBack:backgroundView];
Swift 4 Solution :
#IBInspectable var backgroundImage: UIImage? {
didSet {
UIGraphicsBeginImageContext(self.frame.size)
backgroundImage?.draw(in: self.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image{
self.backgroundColor = UIColor(patternImage: image)
}
}
}
I have a single image I want as the background for my app no matter what viewcontroller they are on - how do you accomplish this?
Here's how you set a background to an image:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Background.png"]];
Edit: To write up what Felixyz said (and thanks to Manni), do this in your delegate:
window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Background.png"]];
And in each view you want to have the image, do this:
self.view.backgroundColor = [UIColor clearColor];
Depends on what sort of interface you have. Tabbed? Navigation based? But the general answer is: add a UIImageView to your UIWindow before/below your main view. Then make every view handled by your main view controller have a transparent background. Hard to give more specific advice without knowing if you use IB or not, or what your view hierarchy looks like.
In my app, I set a default background color. Maybe you can do this with you background image:
1.: Set the background color of your UIWindow in your AppDelegate:
window.backgroundColor = [UIColor myBackgroundGray]; // own Category
2.: And now, make all other views transparent:
self.view.backgroundColor = [UIColor clearColor]; // = transparent
In your AppDelegate in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Add this line :
[self.window setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]]];
After you just have to set your views backgrounds to [UIColor clearColor];
I am not sure of the performance implications, but I needed to accomplish something similar, and ended up using a UIImageView which works well (in C#, but works the same in obj-c):
//Add the view controller first, to ensure proper order of views later.
Window.RootViewController = new UIViewController();
//create backdrop image view
var imageView = new UIImageView(Window.Bounds);
imageView.Image = UIImage.FromBundle("backdrop.jpg");
//insert into window.
Window.InsertSubview(imageView, 0);
This doesn't handle orientation changes, but in my case, allowed me to add motion effects to the backdrop (such as parallax).
Your background is a property of any View-inheriting object. Labels, Buttons, Controllers, and the app window, for example, all have backgrounds. If you want it to be completely a bg for the entire app you must climb the path in your controllers to find the very "top" (bottom-viewed) view, and set its background to be the image you desire.
just call this assignbackground in viewDidLoad
override func viewDidLoad() {
assignbackground()
}
func assignbackground(){
let background = UIImage(named: "background")
var imageview : UIImageView!
imageview = UIImageView(frame: view.bounds)
imageview.contentMode = UIViewContentMode.ScaleAspectFill
imageview.clipsToBounds = true
imageview.image = background
imageview.center = view.center
view.addSubview(imageview)
self.view.sendSubviewToBack(imageview)
}
I usually use this function to avoid overlaps with navigation bar on iphone.
-(void)setImageBackground:(NSString*)imageName{
UINavigationController* navigationController = [self navigationController];
float height = navigationController.toolbar.frame.size.height;
CGSize size = self.view.frame.size;
size.height = size.height;
UIGraphicsBeginImageContext(size);
CGRect bounds = self.view.bounds;
bounds.origin.y = bounds.origin.y + height;
bounds.size.height = bounds.size.height-height;
[[UIImage imageNamed:imageName] drawInRect:bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
}
I am having a lot of trouble trying to find out how to draw a transparent circle on top of a UIImage within my UIImageView. Google-ing gives me clues, but I still can't find a working example.
Are there any examples that anyone knows of that demonstrate this?
Easiest way is simply to create a semi-transparent square UIView, then set the cornerRadius of its layer to be half of its width/height. Something like:
UIView *squareView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
squareView.alpha = 0.5;
squareView.layer.cornerRadius = 50;
...
[squareView release];
This has got to be the simplest solution:
CGFloat r = 150;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1.5*r,1.5*r)];
lbl.text = #"●";
lbl.transform = CGAffineTransformMakeTranslation(0.0f, -r/6);
lbl.textAlignment = UITextAlignmentCenter;
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor redColor];
lbl.font = [UIFont systemFontOfSize:2*r];
lbl.alpha = 0.5;
lbl.center = self.view.center;
[self.view addSubview:lbl];
One way would be to add a CAShapeLayer with a circular path, either directly to the layer of the UIImageView or as the layer of a new UIView that is added to the UIImageView.
If you actually want to modify the image, then create a mutable copy of it by drawing it into a CGBitmapContext then creating a new image from the modified bitmap.
CGPathRef circlePath = CGPathCreateMutable();
CGPathAddEllipseInRect( circlePath , NULL , CGRectMake( 0,0,20,20 ) );
CAShapeLayer *circle = [[CAShapeLayer alloc] init];
circle.path = circlePath;
circle.opacity = 0.5;
[myImageView.layer addSublayer:circle];
CGPathRelease( circlePath );
[circle release];
You can implement a custom sub-class of UIView that draws your image and then the circle in the drawRect method:
#interface CircleImageView : UIView {
UIImage * m_image;
CGRect m_viewRect;
// anything else you need in this view?
}
Implementation of drawRect:
- (void)drawRect:(CGRect)rect {
// first draw the image
[m_image drawInRect:m_viewRect blendMode:kCGBlendModeNormal alpha:1.0];
// then use quartz to draw the circle
CGContextRef context = UIGraphicsGetCurrentContext ()
// stroke and fill black with a 0.5 alpha
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 0.5);
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.5);
// now draw the circle
CGContextFillEllipseInRect (context, m_viewRect);
}
You will need to set up the m_viewRect and m_image member functions on init.