1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.example.android.snake; 18 19import android.content.Context; 20import android.content.res.TypedArray; 21import android.graphics.Canvas; 22import android.graphics.Color; 23import android.graphics.Paint; 24import android.util.AttributeSet; 25import android.view.View; 26 27import java.util.Arrays; 28 29/** 30 * Background View: Draw 4 full-screen RGBY triangles 31 */ 32public class BackgroundView extends View { 33 34 private int[] mColors = new int[4]; 35 36 private final short[] mIndices = 37 { 0, 1, 2, 0, 3, 4, 0, 1, 4 // Corner points for triangles (with offset = 2) 38 }; 39 40 private float[] mVertexPoints = null; 41 42 public BackgroundView(Context context, AttributeSet attrs) { 43 super(context, attrs); 44 setFocusable(true); 45 46 // retrieve colors for 4 segments from styleable properties 47 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BackgroundView); 48 mColors[0] = a.getColor(R.styleable.BackgroundView_colorSegmentOne, Color.RED); 49 mColors[1] = a.getColor(R.styleable.BackgroundView_colorSegmentTwo, Color.YELLOW); 50 mColors[2] = a.getColor(R.styleable.BackgroundView_colorSegmentThree, Color.BLUE); 51 mColors[3] = a.getColor(R.styleable.BackgroundView_colorSegmentFour, Color.GREEN); 52 53 a.recycle(); 54 } 55 56 @Override 57 protected void onDraw(Canvas canvas) { 58 assert(mVertexPoints != null); 59 60 // Colors for each vertex 61 int[] mFillColors = new int[mVertexPoints.length]; 62 63 for (int triangle = 0; triangle < mColors.length; triangle++) { 64 // Set color for all vertex points to current triangle color 65 Arrays.fill(mFillColors, mColors[triangle]); 66 67 // Draw one triangle 68 canvas.drawVertices(Canvas.VertexMode.TRIANGLES, mVertexPoints.length, mVertexPoints, 69 0, null, 0, // No Textures 70 mFillColors, 0, mIndices, 71 triangle * 2, 3, // Use 3 vertices via Index Array with offset 2 72 new Paint()); 73 } 74 } 75 76 @Override 77 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 78 super.onSizeChanged(w, h, oldw, oldh); 79 80 // Construct our center and four corners 81 mVertexPoints = new float[] { 82 w / 2, h / 2, 83 0, 0, 84 w, 0, 85 w, h, 86 0, h 87 }; 88 } 89 90} 91