2010-01-02 34 views
3

在另一篇文章中,luvieere分享了使用QuartzCore框架(see post)将圆角应用于文本视图的方法。在我看来,像UITextField中发现的3D边框可以通过图层创建,而不是使用背景图像。如何使用3D阴影边框设计UITextView?

有谁知道是否或如何做到这一点?我真的很想找到一种方法来添加3D边框,而不必启动图形编辑器并创建3D阴影背景。谢谢!

回答

4

在视图控制器:

newCommentBody.layer.cornerRadius = 7; 
    newCommentBody.clipsToBounds = YES; 

结交新类的TextView继承的UITextView

#import "TextView.h" 
#import <CoreGraphics/CoreGraphics.h> 
#import <CoreGraphics/CGColor.h> 

@implementation TextView 

-(void) drawRect:(CGRect)rect { 
    UIGraphicsBeginImageContext(self.frame.size); 

    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(currentContext, 1.0); //or whatever width you want 
    CGContextSetRGBStrokeColor(currentContext, 0.6, 0.6, .6, 1.0); 

    CGRect myRect = CGContextGetClipBoundingBox(currentContext); 
    //printf("rect = %f,%f,%f,%f\n", myRect.origin.x, myRect.origin.y, myRect.size.width, myRect.size.height); 

    float myShadowColorValues[] = {0,0,0,1}; 
    CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGColorRef colorRef = CGColorCreate(myColorSpace, myShadowColorValues); 
    CGContextSetShadowWithColor(currentContext, CGSizeMake(0, -1), 3, colorRef); 
    // CGContextSetShadow(currentContext, CGSizeMake(0, -1), 3); 

    CGContextStrokeRect(currentContext, myRect); 
    UIImage *backgroundImage = (UIImage *)UIGraphicsGetImageFromCurrentImageContext(); 
    UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
    [myImageView setImage:backgroundImage]; 
    [self addSubview:myImageView]; 
    [backgroundImage release]; 

    UIGraphicsEndImageContext(); 
} 

@end 
+0

这是接近!但是,TextView中的阴影边框不会“粘住”边缘。如果输入的文本大于视图大小(即滚动),则阴影边框将与TextView中的文本一起滚动。需要修改自定义TextView来调整每个文本内容的边框大小。 – DSpeckleback 2010-04-15 17:39:40

+0

您可以通过缩进8个空格来格式化代码。 – kennytm 2010-07-03 15:59:39

+0

对于不滚动的阴影,可以使用textview的框架创建一个“容器”视图,然后绘制阴影,然后在其中添加文本视图。 – 2010-09-16 10:50:25

1
m_txtViewSource.layer.borderWidth = 1; 

m_txtViewSource.layer.borderColor = [[UIColor grayColor] CGColor]; 

它不是3D,但更为简单和安全的代码