1. 程式人生 > >UITextView新增背景圖片

UITextView新增背景圖片

 一、給UITextView繪製圓角,通過QuartzCore框架,操作CALayer可以給UITextView繪製圓角邊框。

       textView.layer.cornerRadius = 6

       textView.layer.masksToBounds = YES

通過cornerRadius可設定圓角弧度。

二、UITextView和UIImageView組合,將背景圖片製作好載入進UIImageView。

      CGRect imageViewFrame = CGRectMake(30.0,100.0,240.0,90.0);

      UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageViewFrame];

      imageView.image = [UIImage imageNamed:@"background.png"];

      imageView.userInteractionEnabled = YES;

      CGRect textViewFrame = CGRectMake(5.0,5.0,230.0,80.0);

      UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame];

      textView.backgroundColor = [UIColor clearColor];

      [imageView addSubview:textView];

設定imageView.userInteractionEnabled = YES,讓textView響應觸碰事件。

三、設定UITextView背景圖片,在UITextView區域內。

      CGRect textViewFrame = CGRectMake(30.0,100.0,240.0,90.0);

      UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame];      

      UIImageView *imageView = [[UIImageView alloc] initWithFrame:[textView bounds]];

      imageView.image = [UIImage imageNamed:@"background.png"];

      [textView addSubview:imageView];

      [textView sendSubviewToBack:imageView];


看到的另一種方法,這個方法我已經實驗過了,可行:

  1. UITextView *textView = [[UITextView alloc]initWithFrame: window.frame];
  2.     textView.text = @"text\n text\n text";
  3.     UIImageView *imgView = [[UIImageView alloc]initWithFrame: textView.frame];
  4.     imgView.image = [UIImage imageNamed: @"myImage.jpg"];
  5.     [self.view addSubview: imgView];
  6.     [self.view sendSubviewToBack: imgView];
  7.     [self.view addSubview: textView];
  8. 但是注意,5,6,7行我修改過,原來的程式碼是:
  9.   [textView addSubview: imgView];
  10.     [textView sendSubviewToBack: imgView];
  11.     [self.view addSubview: textView];
  12. 這樣實際上是把imgview作為了textview的一個字檢視先加進來,然後把textview在加入到當前檢視,這樣做的不好處就是imgview因為是textview的一個字檢視,所以大小跟textview一樣,也就是說你沒法設定整個頁面的背景,如果你的textview不是全屏的話