2012-02-28 84 views
8

這裏是我的形象:如何使我的圖像中的中心IOS水平

Obj *obj = ... obj has imageHref which is NSString 

UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:obj.imageHref]]; 
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; 

取決於圖像大小我無法弄清楚如何居中,任何想法?

這是所有裏面的方法:

- (void)drawRect:(CGRect)rect {  
    Obj *obj = ... obj has imageHref which is NSString 

    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:obj.imageHref]]; 
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; 

    NSLog(@"%f", rect.size.width); 
    NSLog(@"%f", rect.size.height); 
} 

rect.size.width打印320.000000和rect.size.height打印416.000000

回答

32
[image drawInRect:CGRectMake((self.view.frame.size.width/2) - (image.size.width/2), 
          (self.view.frame.size.height/2) - (image.size.height/2), 
          image.size.width, 
          image.size.height)]; 

編輯:

因爲你已經在一個UIView:

[image drawInRect:CGRectMake((self.frame.size.width/2) - (image.size.width/2), (self.frame.size.height/2) - (image.size.height/2), image.size.width, image.size.height)]; 
+0

嗯......有沒有保證的寬度的一個部門或2個住宿爲整數的高度。我會加上'地板'。 – 2013-01-22 16:09:51

23

這個或者非常類似的東西應該水平居中。

CGPoint centerImageView = imageView.center; 
centerImageView.x = self.view.center.x; 
ImageView.center = centerImageView; 
+0

感謝它的工作很好.. – Mani 2012-05-29 11:21:30

+0

中心的屬性找不到類型UIImage – London 2012-06-05 12:05:43

+0

,但它已在UIImageView。我已經更新了我的答案,使其明顯。 – Damo 2013-04-05 10:22:17

1

有可能在.H類文件@interface之前添加這樣一個宏
#define COUNTMID(X,Y) (float) (X-Y)/2
,然後用它的代碼
float center COUNTMID(ParentView.frame.width,ChildView.frame.width)
把你的ChildView鑑於在ParentView的水平中心
我還做了一個方法,使一幀ChildView被放置在ParentView的中心:

-(CGRect) CenterFrameOfView:(UIView *) ParentView forView:(UIView *) ChildView 
{ 
    CGRect result = CGRectMake(COUNTMID(ParentView.frame.size.width,ChildView.frame.size.width),COUNTMID(ParentView.frame.size.height,ChildView.frame.height),ChildView.frame.size.width,ChildView.frame.size.height); 
    return result; 
} 

或用SETFRAME

-(void) CenterFrameOfView:(UIView *) ParentView forView:(UIView *) ChildView 
{ 
    CGRect result = CGRectMake(COUNTMID(ParentView.frame.size.width,ChildView.frame.size.width),COUNTMID(ParentView.frame.size.height,ChildView.frame.height),ChildView.frame.size.width,ChildView.frame.size.height); 
    [ChildView setFrame:result]; 
} 

希望它可以幫助