BitmapShader.java revision b581e6704fc1478bc1dda517502abd3eab2558d6
1/* 2 * Copyright (C) 2007 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 android.graphics; 18 19import android.annotation.NonNull; 20 21/** 22 * Shader used to draw a bitmap as a texture. The bitmap can be repeated or 23 * mirrored by setting the tiling mode. 24 */ 25public class BitmapShader extends Shader { 26 /** 27 * Prevent garbage collection. 28 * @hide 29 */ 30 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 31 public Bitmap mBitmap; 32 33 private int mTileX; 34 private int mTileY; 35 36 /** 37 * Call this to create a new shader that will draw with a bitmap. 38 * 39 * @param bitmap The bitmap to use inside the shader 40 * @param tileX The tiling mode for x to draw the bitmap in. 41 * @param tileY The tiling mode for y to draw the bitmap in. 42 */ 43 public BitmapShader(@NonNull Bitmap bitmap, @NonNull TileMode tileX, @NonNull TileMode tileY) { 44 set(bitmap, tileX, tileY); 45 } 46 47 private BitmapShader(Bitmap bitmap, int tileX, int tileY) { 48 setInternal(bitmap, tileX, tileY); 49 } 50 51 /** 52 * Reinitialize the BitmapShader's Bitmap and tile modes. 53 * 54 * @param bitmap The bitmap to use inside the shader 55 * @param tileX The tiling mode for x to draw the bitmap in. 56 * @param tileY The tiling mode for y to draw the bitmap in. 57 */ 58 public void set(@NonNull Bitmap bitmap, @NonNull TileMode tileX, @NonNull TileMode tileY) { 59 if (tileX == null || tileY == null) { 60 throw new IllegalArgumentException(); 61 } 62 setInternal(bitmap, tileX.nativeInt, tileY.nativeInt); 63 } 64 65 private void setInternal(Bitmap bitmap, int tileX, int tileY) { 66 if (bitmap == null) { 67 throw new IllegalArgumentException("Bitmap must be non-null"); 68 } 69 if (bitmap == mBitmap && tileX == mTileX && tileY == mTileY) { 70 return; 71 } 72 discardNativeInstance(); 73 mBitmap = bitmap; 74 mTileX = tileX; 75 mTileY = tileY; 76 } 77 78 @Override 79 long createNativeInstance(long nativeMatrix) { 80 return nativeCreate(nativeMatrix, mBitmap, mTileX, mTileY); 81 } 82 83 /** 84 * @hide 85 */ 86 @Override 87 protected Shader copy() { 88 final BitmapShader copy = new BitmapShader(mBitmap, mTileX, mTileY); 89 copyLocalMatrix(copy); 90 return copy; 91 } 92 93 private static native long nativeCreate(long nativeMatrix, Bitmap bitmap, 94 int shaderTileModeX, int shaderTileModeY); 95} 96