zoukankan      html  css  js  c++  java
  • ios 在View里绘图

    1、新建ViewBasedApplication

    2、添加一个新的objective-c class,并设置为UIView的子类,可以命名为MyView

    3、重写MyView的方法

    - (void)drawRect:(CGRect)rect
    这个方法是在MyView里定义的,重写这个方法可以显示自己重绘的内容

    在方法内,添加以下代码,实现渐变颜色

    CGContextRef context = UIGraphicsGetCurrentContext();
        CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
        CGFloat colors[] =
        {
            204.0 / 255.0, 224.0 / 255.0, 244.0 / 255.0, 1.00,
            29.0 / 255.0, 156.0 / 255.0, 215.0 / 255.0, 1.00,
            0.0 / 255.0,  50.0 / 255.0, 126.0 / 255.0, 1.00,
        };
        CGGradientRef gradient = CGGradientCreateWithColorComponents      
        (rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
        CGColorSpaceRelease(rgb);    
        CGContextDrawLinearGradient(context, gradient,CGPointMake    
                                    (0.0,0.0) ,CGPointMake(0.0,self.frame.size.height),                    
                                    kCGGradientDrawsBeforeStartLocation);

    以下代码可以在视图屏幕上画出一个字符

    UIColor *magentaColor =
        [UIColor colorWithRed:0.5f
                        green:0.0f
                         blue:0.5f
                        alpha:1.0f];
        /* Set the color in the graphical context */
        [magentaColor set];
        /* Load the font */
        UIFont *helveticaBold =
        [UIFont fontWithName:@"HelveticaNeue-Bold"
                        size:30.0f];
        /* Our string to be drawn */
        NSString *myString = @"Angry bird";
        /* Draw the string using the font. The color has
         already been set */
        [myString drawAtPoint:CGPointMake(25, 190)
                     withFont:helveticaBold];

    然后在屏幕上画出一条斜线

    CGContextRef ref=UIGraphicsGetCurrentContext();//拿到当前被准备好的画板。在这个画板上画就是在当前视图上画
        
        CGContextBeginPath(ref);//这里提到一个很重要的概念叫路径(path),其实就是告诉画板环境,我们要开始画了,你记下。
        
        CGContextMoveToPoint(ref, 0, 0);//画线需要我解释吗?不用了吧?就是两点确定一条直线了。
        
        CGContextAddLineToPoint(ref, 300,300);
        
        CGFloat redColor[4]={1.0,0,0,1.0};
        
        CGContextSetStrokeColor(ref, redColor);//设置了一下当前那个画笔的颜色。画笔啊!你记着我前面说的windows画图板吗?
        
        CGContextStrokePath(ref);//告诉画板,对我移动的路径用画笔画一下。

    在ViewController里重写方法(我这里叫game01ViewController,里新建项目时自动生成的,继承于UIViewController)

    @interface game01ViewController : UIViewController {

    - (void) loadView {
        MyView *view = [[MyView alloc] init];
        self.view = view;
    }
     实例化MyView,然后将控制器的view属性设为MyView的对象view,这样就可以了

  • 相关阅读:
    抛开BlazeDS,自定义flex RPC
    设计模式学习03装饰器模式
    通过ANT生成MANIFEST.MF中的ClassPath属性
    Spring JDBCTemplate与Hiberante混用
    关于 两个 datetime 列的差别导致了运行时溢出
    在Wcf中使用Nhibernate (续)
    sql2005/sql2008 分页
    工行支付api查询asp.net C# 实现
    生成静态页面的vbscript
    Asp.net Mvc Post ID Bug
  • 原文地址:https://www.cnblogs.com/yuanxiaoping_21cn_com/p/2415718.html
Copyright © 2011-2022 走看看