天天看点

使用Shader渲染图形

public class ShaderActivity extends Activity {
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        MyView myView = new MyView(this);
        
        setContentView(myView);
        
    }
    
    public class MyView extends View{
    	//声明BitMap对象
    	private Bitmap bitmap;
    	//声明位图渲染图像
    	private Shader bitmapShader;
    	//声明线性渲染对象
    	private Shader linerGradient;
    	//声明光束渲染对象
    	private Shader radialGradient;
    	//声明梯度渲染对象
    	private Shader sweepGradient;
    	//声明混合渲染对象
    	private Shader composeGradient;
    	
    	private Paint paint;
    	//声明颜色数组
    	private int[] colors;
    	private boolean isFrist = true;
		/**
		 * @param context
		 */
		public MyView(Context context) {
			super(context);
			//获得BitMap实例
	        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.openning);
	        //实例化画笔
	        paint = new Paint();
	        colors = new int[]{Color.RED,Color.GREEN,Color.BLUE};
	        
	        //实例化位图渲染对象,X坐标方向重复图形,	Y坐标方向镜像图形
	        bitmapShader = new BitmapShader(bitmap,TileMode.REPEAT,TileMode.MIRROR);
	        //实例化线性对象
	        linerGradient = new LinearGradient(0, 0, 100, 100, colors, null, TileMode.REPEAT);
	        //实例化光束
	        radialGradient = new RadialGradient(100,100,80,colors,null,TileMode.REPEAT);
	        //实例化梯度
	        sweepGradient = new SweepGradient(200,200,colors,null);
	        //实例化混合
	        composeGradient = new ComposeShader(linerGradient,radialGradient,PorterDuff.Mode.DARKEN);
	        
	        setFocusable(true);
		}
    	/* (non-Javadoc)
    	 * @see android.view.View#onDraw(android.graphics.Canvas)
    	 */
    	@Override
    	protected void onDraw(Canvas canvas) {
    		super.onDraw(canvas);
    		if(isFrist){
    			String content = "按上、下、左、右、中间键测试";
    			paint.setColor(Color.BLUE);
    			canvas.drawText(content, 0, content.length()-1, 20,20,paint);
    			
    		}else{
    			//全屏画矩形
    			canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
    		}
    	}
    	
    	/* (non-Javadoc)
    	 * @see android.view.View#onKeyDown(int, android.view.KeyEvent)
    	 */
    	@Override
    	public boolean onKeyDown(int keyCode, KeyEvent event) {
    		isFrist = false;
    		if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
    			paint.setShader(bitmapShader);
    		}
    		
    		if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
    			paint.setShader(linerGradient);
    		}
    		
    		if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
    			paint.setShader(radialGradient);
    		}
    		
    		if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
    			paint.setShader(sweepGradient);
    		}
    		
    		if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
    			paint.setShader(composeGradient);
    		}
    		//重绘界面
    		postInvalidate();
    		return super.onKeyDown(keyCode, event);
    	}
    }
}