【问题标题】:How to style UITextView with a 3D shadowed border?如何使用 3D 阴影边框设置 UITextView 样式?
【发布时间】:2010-01-02 15:04:07
【问题描述】:

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

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

【问题讨论】:

    标签: iphone 3d coding-style uitextview border


    【解决方案1】:

    在视图控制器中:

        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
    

    【讨论】:

    • 这很接近了!但是,TextView 中的阴影边框不会“粘住”边缘。如果输入的文本大于视图大小(即滚动),阴影边框将与 TextView 中的文本一起滚动。需要修改自定义 TextView 以根据文本内容调整边框大小。
    • 为了让阴影不滚动,你可以用textview的框架创建一个“容器”视图,绘制阴影然后在里面添加textview。
    • 是我正在寻找的一个很好的解决方案。刚刚复制和粘贴,它完全没有问题。
    • 我也尝试实现它 - 但是我得到黑色背景而不是 3D 阴影。知道为什么吗?
    【解决方案2】:
    m_txtViewSource.layer.borderWidth = 1;
    
    m_txtViewSource.layer.borderColor = [[UIColor grayColor] CGColor];
    

    不是 3D,而是更简单安全的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多