2010-08-03 57 views
2

我在试图找出如何在UIImageView内的UIImage顶部绘制透明圆圈时遇到了很多麻烦。谷歌给我提供了线索,但我仍然找不到一个工作的例子。在UIImage上绘制一个透明的圆 - iPhone SDK

有没有任何人知道这个证明的例子?

+2

但是..你怎么看到一个透明的圆?它不是已经在那里吗? – mvds 2010-08-03 01:11:00

+0

我假设他的意思是一个半透明的圆圈... – RedBlueThing 2010-08-03 01:14:06

+0

@mvds你的意见,但是很有趣,并不是真的很有帮助;) – RedBlueThing 2010-08-03 01:14:52

回答

11

最简单的方法是简单地创建一个半透明正方形的UIView,然后将其层的cornerRadius是其一半的宽度/高度的。例如:

UIView *squareView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)]; 
squareView.alpha = 0.5; 
squareView.layer.cornerRadius = 50; 
... 
[squareView release]; 
+3

您忘记了squareView.clipsToBounds = YES;没有它,这是行不通的。 – bstahlhood 2010-08-30 01:38:34

+1

只有当你想在其上添加另一个视图时,但这是一个不同的故事。 – iamj4de 2010-08-31 10:28:34

1

一种方法是将CAShapeLayer与圆形path直接添加到UIImageView的图层或作为添加到UIImageView中的新UIView的图层。

如果您确实想要修改图像,请通过将其绘制到CGBitmapContext中,然后通过修改的位图创建新图像来创建该图像的可变副本。

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]; 
1

可以实现自定义子类的UIView绘制图像,然后将圆在的drawRect方法:

@interface CircleImageView : UIView { 
    UIImage * m_image; 
    CGRect m_viewRect; 

    // anything else you need in this view? 
} 

的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); 
} 

您将需要设置m_viewRectm_image init上的成员函数。

2

得到是最简单的解决方案:

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]; 
+0

左边的领域真棒! :P – RedBlueThing 2010-08-03 01:36:13

+0

即使有基线更正! – mvds 2010-08-03 01:50:42

+0

检查我的一个更简单的方法:-P(少代码)。 – iamj4de 2010-08-03 07:54:58